我使用awk substr()
从字符串中提取一个子字符串。
例如,如果我的字符串是这样的:
qwertyuiop
我想提取(1-3)和(6-9)个字符,我使用下面的代码:
awk '{print (substr($1, 1, 3) substr($1, 6, 4))}'
qweyui
如何将一个特定的减法重复几次?
例如,我想提取(1-3) & (6-9)(6-9)(6-9) (6-9)个字符,得到如下结果:
qweyuioyuioyuio
当然,我可以使用这样的命令:
awk '{print (substr($1, 1, 3) substr($1, 6, 4) substr($1, 6, 4) substr($1, 6, 4))}'
有没有更简单的方法?
发布于 2013-02-12 04:24:18
这是解决此类问题的方法之一(混乱但有效)。
echo qwertyuiop | awk '{m=substr($1, 6, 4); {while (count++<3) string=string m;
print substr($1, 1, 3) string}}'
qweyuioyuioyuio
发布于 2013-02-12 06:54:44
如果你想提取不重叠的子串,你可以使用gawk的固定列宽选项:
echo "qwertyuiop" | gawk -v FIELDWIDTHS="3 2 4" '{ print $1 $3 $3 $3 }'
您将定义3个列。第一个字符串的宽度为3个字符(与substr($1,1,3)相同)。第二个是2个字符宽(我们将忽略它)。第三个是第二个子字符串(substr($1,6,4))。
您可以直接打印已定义的字段。
请参阅https://www.gnu.org/software/gawk/manual/gawk.html#Constant-Size
发布于 2013-02-12 02:59:36
有一个delightful post解释了在awk中重复字符串的各种方式。
我将引用最明显的:
function rep1(s,n, r) {
# O(n) allocate/appends
# 2 lines of code
# This is the simplest possible solution that will work:
# just repeatedly append the input string onto the value
# that will be passed back, decrementing the input count
# until it reaches zero.
while (n-->0) r = r s;
return r;
}
PS:awk
中函数参数前有大量空格,说明此参数被用作临时局部变量。
https://stackoverflow.com/questions/14818233
复制相似问题