![](/img/trans.png)
[英]How to replace all instances of a character except the last n instances in each line of a file in Bash
[英]How to append a character after N patterns at each line in bash?
如何在每行第二个字符','之后插入','?
我想要以下内容:
input.txt
a,b,c,d,e
e,f,g,
h,,i
output.txt
a,b,,c,d,e
e,f,,g
h,,,i
提前致谢
awk
解救!
$ awk -F, -v OFS=, '{$3=OFS $3}1' file
a,b,,c,d,e
e,f,,g,
h,,,i
在第二个之后,
是第三个字段。 在第三个字段前面加上,
然后打印。
或者,将列号作为参数并编写一次定界符。
$ awk -F, -v c=3 'BEGIN{OFS=FS} {$c=OFS $c}1' file
这可以理解为“在位置3插入新列”。 请注意,添加第六行也可以使用sed
复制它。
$ awk -F, -v c=6 'BEGIN{OFS=FS} {$c=OFS $c}1' file
a,b,c,d,e,,
e,f,g,,,,
h,,i,,,,
输入
$ cat input
a,b,c,d,e
e,f,g,
h,,i
使用sed像:
$ N=2
$ cat input | sed "s/,/&,/${N}"
a,b,,c,d,e
e,f,,g,
h,,,i
$ N=3
$ cat input | sed "s/,/&,/${N}"
a,b,c,,d,e
e,f,g,,
h,,i
您可以更改N。
s/pattern/replacement/flags
用替换字符串替换模式。 替代函数中的标志的值是零或更大的以下值:
N Make the substitution only for the N'th occurrence
g Make the substitution for all
对于函数s/,/&,/${N}
,找到第N个逗号并将其替换为两个逗号(替换中出现的&符( &
)替换为模式字符串)。 $ {N}只是一个变量。
顺便说一句,如果要插入,“”,需要转义特殊字符双引号。
使用sed
:
sed -E 's/^([^,]*,[^,]*,)(.*)/\1,\2/' file.txt
例:
% cat file.txt
a,b,c,d,e
e,f,g,
h,,i
% sed -E 's/^([^,]*,[^,]*,)(.*)/\1,\2/' file.txt
a,b,,c,d,e
e,f,,g,
h,,,i
您可以像这样使用sed
:
sed 's/^[^,]*,[^,]*/&,/' file
a,b,,c,d,e
e,f,,g,
h,,,i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.