Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have the following list of words:

name,id,3 

I need to have it double quoted like this:

"name,id,3" 

I have tried sed 's/.*/\"&\"/g' and got:

"name,id,3 

Which has only one double quote and is missing the closing double quote.

I've also tried awk {print "\""$1"\""} with exactly the same result. I need help.

like image 227
minerals Avatar asked May 25 '12 12:05

minerals


People also ask

Can you use double quotes with SED?

@DummyHead Here's another approach: if you use single quotes, the sed command is exactly as you type it. If you use double quotes, you must take into account all shell substitutions and elaborations to "visualize" what command is eventually passed on to sed.

How do you add a double quote to a string in Unix?

If you want to print double quote in the output then you have to use the backslash (\) with the string. In a similar way, you can print backticks (`) and backslash(\) characters in the output by using the backslash(\) within the double quotation.

How do you add double quotes in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex. However, because Java uses double quotes to delimit String constants, if you want to create a string in Java with a double quote in it, you must escape them.

How do you add a double quote to a string?

To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark. For example, to create the preceding string, use the following code.


1 Answers

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" 
like image 182
0xC0000022L Avatar answered Sep 20 '22 14:09

0xC0000022L