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

后端 未结 4 1562
鱼传尺愫
鱼传尺愫 2021-02-02 09:21

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

It put a $ at the beginning of every line.

相关标签:
4条回答
  • 2021-02-02 10:03

    shorter

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

    without spaces

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

    skip empty lines

    sed '/^ *$/d;s/.*/"&"/'
    
    0 讨论(0)
  • 2021-02-02 10:05

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

    sed 's/^.*$/"&"/g' file.txt
    
    0 讨论(0)
  • 2021-02-02 10:11

    here it is

    sed 's/\(.*\)/"\1"/g'
    
    0 讨论(0)
  • 2021-02-02 10:17

    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.

    0 讨论(0)
提交回复
热议问题