How to enclose every line in a file in double quotes with sed?
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.
nw.
Updated on July 10, 2020Comments
-
nw. almost 4 years
This is what I tried:
sed -i 's/^.*/"$&"/' myFile.txt
It put a $ at the beginning of every line.
-
nw. almost 13 yearshmm, this one seems to have no effect at all.
-
nw. almost 13 yearsdo i need to escape double quotes in powershell or something?
-
funroll over 9 yearsWorks great on OS X Yosemite.
-
funroll almost 9 yearsIf you understand the magic of sed, can you explain what this is actually doing?
-
Josh Padnick over 8 yearsFor unix/linux beginners, you may want to do something like
cat filename.txt | sed 's/\(.*\)/"\1"/g'
to feed your input into sed. -
ASten over 7 yearsI've tried all the answers listed above, nothing works for me but this trick does! Thanks.
-
Backgammon about 5 years
cat file | <thing>
is a classically incorrect use ofcat
. Use file redirection to pass files into standard input:sed 's/\(.*\)/"\1"/g' < filename.txt
.