How to add double quotes to a line with SED or AWK?

前端 未结 6 1994
不知归路
不知归路 2020-12-29 23:32

I have the following list of words:

name,id,3

I need to have it double quoted like this:

\"name,id,3\"

I

相关标签:
6条回答
  • 2020-12-29 23:58

    Before using sed command, you can use \ as escape character then it will print " in your string. As an example, i put the similar string to first line of a text file with below command:

    var = "\"name,id,3\""
    sed -i '1i' "$var" /tmp/out.txt
    
    0 讨论(0)
  • 2020-12-30 00:00

    Use this to pipe your input into:

    sed 's/^/"/;s/$/"/'
    

    ^ is the anchor for line start and $ the anchor for line end. With the sed line we're replacing the line start and the line end with " and " respectively.

    Example:

    $ echo -e "name,id,2\nname,id,3\nname,id,4"|sed 's/^/"/;s/$/"/'
    "name,id,2"
    "name,id,3"
    "name,id,4"
    

    without the sed:

    $ echo -e "name,id,2\nname,id,3\nname,id,4"
    name,id,2
    name,id,3
    name,id,4
    

    Your file seems to have DOS line endings. Pipe it through dos2unix first.

    Proof:

    $ cat test.txt
    name,id,2
    name,id,3
    name,id,4
    $ sed 's/^/"/;s/$/"/' test.txt
    "name,id,2
    "name,id,3
    "name,id,4
    $ cat test.txt|dos2unix|sed 's/^/"/;s/$/"/'
    "name,id,2"
    "name,id,3"
    "name,id,4"
    
    0 讨论(0)
  • 2020-12-30 00:05

    You can use awk instead of sed like this:

    line='name,id,3'
    echo $line | awk '{printf("\"%s\"\n", $0);}'
    

    OR even better is to use BASH printf like this:

    printf '"%s"\n' $line
    
    0 讨论(0)
  • 2020-12-30 00:05

    Simplest way I've found is to use the HEX codes for double quotes:

     echo name,id,3 | awk '{print "\x22" $1 "\x22"}'
     "name,id,3"
    
    0 讨论(0)
  • 2020-12-30 00:10

    Similar to @Dennis solution,

    Use

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

    No need to look for '\r', This will apply double quote for all strings. This does not require run dos2unix on the input file.

    0 讨论(0)
  • 2020-12-30 00:12

    Your input file has carriage returns at the end of the lines. You need to use dos2unix on the file to remove them. Or you can do this:

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

    which will remove the carriage return and add the quotes.

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