![](/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.