33

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

It put a $ at the beginning of every line.

anubhava
  • 761,203
  • 64
  • 569
  • 643
nw.
  • 4,795
  • 8
  • 37
  • 42
  • have you tried to remove the ampersand? – Karoly Horvath Jul 01 '11 at 23:21
  • Sorry, I mean to say it put a $ at the beginning of each line. Edited. Without the ampersand it does nothing – nw. Jul 01 '11 at 23:30
  • both work fine here.. I have no idea what kind of sed you are using – Karoly Horvath Jul 01 '11 at 23:36
  • The `&` does not need the `$`, you're just getting a literal `$`. Based on your comments I think you have a shell quoting problem, not a `sed` problem. – Ben Jackson Jul 01 '11 at 23:37
  • This worked: 's/^.*$/\"&\"/'.   I had to escape the double quotes (but with sed's escape character, not powershell's). I am using sed from GnuWin32. Is this not necessary using other builds of sed? – nw. Jul 01 '11 at 23:54
  • http://stackoverflow.com/questions/6714165/powershell-stripping-double-quotes-from-command-line-arguments – nw. Jul 19 '11 at 00:42

4 Answers4

47

here it is

sed 's/\(.*\)/"\1"/g'
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
22

shorter

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

without spaces

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

skip empty lines

sed '/^ *$/d;s/.*/"&"/'
clt60
  • 62,119
  • 17
  • 107
  • 194
6

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

sed 's/^.*$/"&"/g' file.txt
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

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.

Julian de Bhal
  • 901
  • 9
  • 12