Wednesday, September 25, 2019

regex - Add a string to the beginning of a line containing a pattern




I am trying to comment the lines in my scripts where a pattern from a given list of patterns is present. Now, I am able to do it the following way on command line :




sed '/abcdefg/ s/^/#/' file.sql > file.commented


But if I use a variable for pattern (instead of abcdefg directly as above) I'm not able to do the same.



pattern=abcdefg
sed '/$pattern/ s/^/#/' file.sql > file.commented


Looks like it is escaping the dollar character and not taking the value of the variable.




How do you do the same with awk?


Answer



You need to use double quote to make it work with variables in shell:



sed "/$pattern/ s/^/#/" file.sql > file.commented


You can also use inline feature of shell to save changes in input file itself




sed -i.bak "/$pattern/ s/^/#/" file.sql


However it is best to avoid sed for this job since it uses regex and above command will break if $pattern contains / or some special regex meta character. Better to use awk like this:



awk -v p="$pattern" 'index($0, p) {$0 = "#" $0} 1' file.sql > file.commented

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...