gpt4 book ai didi

bash - 如何定义单词的参数?

转载 作者:行者123 更新时间:2023-11-29 09:18:06 26 4
gpt4 key购买 nike

我想做的是在每个字符前后获取 2 个字符串。

输入文件:

hello

reader

.....

预期的输出是:

# # h e l //before character h is null and assign with '#". After character h are "e" and "l".
# h e l l //before character e is "h". After character e are "l" and "l".
h e l l o //before character l are "h" and "e". After character l are "l" and "o".
e l l o # //before character l are "e" and "l". After character l is "o".
l l o # # //before character o are "l" and "l". After character o is null and assign with '#".

# # r e a
# r e a d
r e a d e
e a d e r
a d e r #
d e r # #

这是代码:归功于 RudiC

awk '
{ L = length * 2
M = int (L / 4)
X = sprintf ("%*sY%*s", M, "", M, "")
gsub (/ /, "#", X)
sub (/Y/, $1, X)
gsub (/./, "& ", X)
for (i=1; i<=L; i+=2) print substr (X, i, L-1)
}
' $1

但第一个词只起作用

# # h e l
# h e l l
h e l l o
e l l o #
l l o # #
# # # r e a
# # r e a d
# r e a d e
r e a d e r
e a d e r #
a d e r # #

最佳答案

我会用这样的东西:

awk '{n=length($0)                    # get the length N of the string
$0 = "##" $0 "##" # prepend and append "##"
gsub(/./, "& ") # add a space after every character
for (i=1; i<=2*n; i+=2) # loop X from position 1 to length of the string
print substr($0, i, 5*2-1) # print 5*2 chars from position 2X (-1 for the trailing space)
print ""}' file # print an empty line to separate blocks

查看实际效果:

$ awk '{n=length($0); $0 = "##" $0 "##"; gsub(/./, "& "); {for (i=1; i<=2*n; i+=2) print substr($0, i, 5*2)} print ""}' file
# # h e l
# h e l l
h e l l o
e l l o #
l l o # #

# # r e a
# r e a d
r e a d e
e a d e r
a d e r #
d e r # #

如您所见,这里的关键是硬编码要打印的字符数,而不是依赖于字符串的长度。就我而言,我将其设置为 5。

关于bash - 如何定义单词的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37455542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com