4

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Ajim Bagwan
  • 127
  • 3
  • 10
  • 1
    Did you waste ten seconds looking for an answer here in StackOverflow? This question has been asked and solved hundreds of times. – Birei Feb 20 '15 at 09:54
  • Well, sorry about that. But I searched for it yesterday too and tried different things before spending/wasting my time here. I will delete the question. – Ajim Bagwan Feb 20 '15 at 09:57
  • @AjimBagwan: Don't delete the question since answer with non-regex options has been posted below, that might help other readers on SO. – anubhava Feb 20 '15 at 09:58
  • 2
    @AjimBagwan: In my opinion once you asked it, there is no need to delete it because some users took their time to help you. – Birei Feb 20 '15 at 10:00

1 Answers1

3

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
anubhava
  • 761,203
  • 64
  • 569
  • 643