krb686
krb686

Reputation: 1796

Adding quotations at beginning and end of a line using 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?

Upvotes: 10

Views: 9502

Answers (3)

Priyajit Bera
Priyajit Bera

Reputation: 1

sed -e 's/^/"/' -e 's/$/"/' filename.txt
"tag1"
"tag2"

This serves your purpose also you can change the double quotes(") with required any other pattern also, like:

sed -e 's/^/<<</' -e 's/$/>>>' data.txt
<<<tag1>>>
<<tag2>>>

Upvotes: 0

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed 's/.*/"&"/' YourFile 

Will do the same using full line as pattern replacement &.

In this case g is not needed because you only have 1 occurrence of the whole line per line (default behaviour of sed reading line by line)

Upvotes: 9

fedorqui
fedorqui

Reputation: 289835

[^$] 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"

Upvotes: 6

Related Questions