简体   繁体   中英

How to append a character after N patterns at each line in bash?

How can I insert a ',' after the 2nd character ',' at each line ?

I want the following :

input.txt

a,b,c,d,e
e,f,g,
h,,i

output.txt

a,b,,c,d,e
e,f,,g
h,,,i

Thanks in advance

awk to the rescue!

$ awk -F, -v OFS=, '{$3=OFS $3}1' file
a,b,,c,d,e
e,f,,g,
h,,,i

after second , is the third field. Prefix the third field with , and print.

Or, making the column number a parameter and writing delimiter once.

$ awk -F, -v c=3 'BEGIN{OFS=FS} {$c=OFS $c}1' file

This can be read as "insert a new column at position 3". Note that this will also work, adding the 6th column, which will be hard to replicate with sed .

$ awk -F, -v c=6 'BEGIN{OFS=FS} {$c=OFS $c}1' file

a,b,c,d,e,,
e,f,g,,,,
h,,i,,,,

input

$ cat input 
a,b,c,d,e
e,f,g,
h,,i

using sed like:

$ 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

you can change the N.


s/pattern/replacement/flags

Substitute the replacement string for the pattern. The value of flags in substitute function is zero or more of the following:

N       Make the substitution only for the N'th occurrence 
g       Make the substitution for all

for function s/,/&,/${N} , it is find the N'th comma and replace it with two commas (An ampersand ( & ) appearing in the replacement is replaced by the pattern string). And ${N} just is a variable.

BTW, you need to escape the special character double quote if you want to insert ,""

Using sed :

sed -E 's/^([^,]*,[^,]*,)(.*)/\1,\2/' file.txt

Example:

% 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

You can use sed like this:

sed 's/^[^,]*,[^,]*/&,/' file

a,b,,c,d,e
e,f,,g,
h,,,i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM