Ashutosh Narayan
Ashutosh Narayan

Reputation: 135

How can I insert double quotes (") between two columns using sed/awk/perl

I have a file with contents:

Version:2.0

I need an output in the following format:

"Version":"2.0"

How should I insert double quotes in these columns ?

Upvotes: 2

Views: 1077

Answers (7)

Thor
Thor

Reputation: 47099

Here's another sed alternative:

echo Version:2.0 | sed 's/[^:]*/"&"/g'

Output:

"Version":"2.0"

Upvotes: 1

zb226
zb226

Reputation: 10500

In perl, you can do it like this:

perl -pe "s/([^:]+):(.+)/\"\1\":\"\2\"/" YourTextFile.txt

Edit 1: In Linux, using $1 and $2 instead of \1 and \2 causes the strings that should be quoted to be empty - the output is then '"":""'. I think this due to the dollar $ being a special character in some *nix shells. Escaping the dollars works as well:

perl -pe "s/([^:]+):(.+)/\"\$1\":\"\$2\"/" YourTextFile.txt

Edit 2: As @TLP suggested, using single quotes is the way to go for *nix, as it avoids shell interpolation and also allows to drop all of the escapes.

perl -pe 's/([^:]+):(.+)/"$1":"$2"/' YourTextFile.txt

Upvotes: 0

TLP
TLP

Reputation: 67910

Simple one-liner:

perl -plwe 's/([^:]+)/"$1"/g'

Take anything that is not a colon and put quotes around it. Because of the -l option we avoid this including the newline at the end.

Upvotes: 3

vyegorov
vyegorov

Reputation: 22885

I think this awk snippet might help:

gawk -F: '{gsub("\"", "\"\""); \
  for(i=1;i<NF;i++) printf("\"%s\":",$i); \
  printf("\"%s\"\n",$NF); }' testfile

It does extra job and doubles existsing quotes.

And to create test file I've used the following code:

cat << EODATA > testfile
Version:2.0
Some:field:with:double(")quotes
EODATA

Upvotes: 0

Borodin
Borodin

Reputation: 126722

 perl -lpe'$_ = join ":",map qq{"$_"},split /:/' myfile

Upvotes: 1

Vijay
Vijay

Reputation: 67231

awk -F":" -v OFS=":" '{for(i=1;i<=NF;i++){$i="\""$i"\"";}print}' 

tested:

> echo "Version:2.0" | awk -F":" -v OFS=":" '{for(i=1;i<=NF;i++){$i="\""$i"\"";}print}'
"Version":"2.0"

or

perl -F -lane 'for(@F){$_="\"".$_."\"";}print join ":",@F'

Upvotes: 1

Kent
Kent

Reputation: 195069

sed -r 's/(^|$)/"/g;s/:/":"/' file

kent$  echo "Version:2.0"|sed -r 's/(^|$)/"/g;s/:/":"/'  
"Version":"2.0"

Upvotes: 1

Related Questions