Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding quotations at beginning and end of a line using sed

Tags:

regex

sed

I know sed 's/^/"/g' works for the beginning of a line, and sed 's/$/"/g' works for the end, but why doesn't sed 's/[^$]/"/g' work for both?

like image 599
krb686 Avatar asked May 26 '15 13:05

krb686


1 Answers

[^$] means "any character except the dollar sign". So saying sed 's/[^$]/"/g' you are replacing all characters with ", except $ (credits to Ed Morton):

$ echo 'he^llo$you' | sed 's/[^$]/"/g'
""""""$"""

To say: match either ^ or $, you need to use the ( | ) expression:

sed 's/\(^\|$\)/"/g' file

or, if you have -r in your sed:

sed -r 's/(^|$)/"/g' file

Test

$ cat a
hello
bye
$ sed -r 's/(^|$)/"/g' a
"hello"
"bye"
like image 120
fedorqui 'SO stop harming' Avatar answered Sep 21 '22 03:09

fedorqui 'SO stop harming'