Use sed to add character in n’th position of matching string

sedtext processing

I need to add a character in the n'th position (in this case 2nd) of a matching string.
For example, in a file text.txt I would like to add an N before the string and after the " only in the strings that contain blah

text.txt:

"1blah8","na","8blah4"  
"2blah5","na","10blah4"  
"5blah5","na","1blah234"  

I want to get a text2.txt:

"Ν1blah8","na","Ν8blah4"  
"Ν2blah5","na","Ν10blah4"  
"Ν5blah5","na","Ν1blah234"  

I have tried sed 's/.*blah.*/N&/' text.txt > text2.txt
but I get the N before the " and only in the first found string of each line.

Best Answer

Another approach:

$ sed 's/"\([^"]*blah[^"]*"\)/"N\1/g' test.txt 
"N1blah8","na","N8blah4"  
"N2blah5","na","N10blah4"  
"N5blah5","na","1blah234

The regex is looking for a ", then 0 or more non-" characters followed by a blah, and then then 0 or more non-" again. Because of the parentheses, this is captured and can later be referred to as \1. Therefore, the command will substitute the matched pattern with itself (\1) but with a "N appended. That's why the first " is outside the parentheses. The /g modifier at the end makes it subsstitute all matching string in each line.

If your sed version supports it, you can simplify it to:

sed -E 's/"([^"]*blah[^"]*")/"N\1/g'
Related Question