La-D La-D - 4 months ago 13
Bash Question

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

Answer

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 ,""

Comments