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

前端 未结 6 2018
不知归路
不知归路 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-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"
    

提交回复
热议问题