How to enclose every line in a file in double quotes with sed?

20,856

Solution 1

here it is

sed 's/\(.*\)/"\1"/g'

Solution 2

shorter

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

without spaces

sed 's/ *\(.*\) *$/"\1"/'

skip empty lines

sed '/^ *$/d;s/.*/"&"/'

Solution 3

You almost got it right. Try this slightly modified version:

sed 's/^.*$/"&"/g' file.txt

Solution 4

You can also do it without a capture group:

sed 's/^\|$/"/g'

'^' matches the beginning of the line, and '$' matches the end of the line.

The | is an "Alternation", It just means "OR". It needs to be escaped here[1], so in english ^\|$ means "the beginning or the end of the line".

"Replacing" these characters is fine, it just appends text to the beginning at the end, so we can substitute for ", and add the g on the end for a global search to match both at once.

[1] Unfortunately, it turns out that | is not part of the POSIX "Basic Regular Expressions" but part of "enhanced" functionality that can be compiled in with the REG_ENHANCED flag, but is not by default on OSX, so you're safer with a proper basic capture group like s/^\(.*\)$/"\1"/

Humble pie for me today.

Share:
20,856
nw.
Author by

nw.

Updated on July 10, 2020

Comments

  • nw.
    nw. almost 4 years

    This is what I tried: sed -i 's/^.*/"$&"/' myFile.txt

    It put a $ at the beginning of every line.

  • nw.
    nw. almost 13 years
    hmm, this one seems to have no effect at all.
  • nw.
    nw. almost 13 years
    do i need to escape double quotes in powershell or something?
  • funroll
    funroll over 9 years
    Works great on OS X Yosemite.
  • funroll
    funroll almost 9 years
    If you understand the magic of sed, can you explain what this is actually doing?
  • Josh Padnick
    Josh Padnick over 8 years
    For unix/linux beginners, you may want to do something like cat filename.txt | sed 's/\(.*\)/"\1"/g' to feed your input into sed.
  • ASten
    ASten over 7 years
    I've tried all the answers listed above, nothing works for me but this trick does! Thanks.
  • Backgammon
    Backgammon about 5 years
    cat file | <thing> is a classically incorrect use of cat. Use file redirection to pass files into standard input: sed 's/\(.*\)/"\1"/g' < filename.txt.