p0ptha5tack
p0ptha5tack

Reputation: 53

Need to manipulate string data using bash

I have data being displayed on the console in the following format:

 "name1",
 "value1",
 "name2",
 "value2",
 "name3",
 "value3",
 ...
 ...

I need to somehow manipulate this output so that it will be displayed in the following format:

 name1 : value1
 name2 : value2
 name3 : value3
 ...
 ...

I'm not very good with shell scripting but I know my options are sed, tr, or awk (or a combination of the aforementioned). I just can't figure out how to accomplish what it is I need here. Thanks in advance!

Upvotes: 1

Views: 44

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80992

glenn jackmans' paste solution is quite elegant but I figured I'd throw in some other solutions.

With sed : sed -ne '1~2{s/$/ : /;N;s/[",]\|\n //g;p}'

For every odd line add : to the end, read the next line into the current pattern space (N), remove any quotes and commas and newline+space combinations and print.

With awk : awk '{gsub(/[",]|^ */,"")} NR%2{printf $0 " : "} !(NR%2)'

Replace all quotes, commas and line-leading sapces. For all odd lines (lines where NR%2 is non-zero) append : and print without a newline. For all even lines (lines where NR%2 is zero) print the line (finishing the previous line).

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247012

Pipe it into:

 | sed 's/^ *"\|", *$//g' | paste -d: - -

sed to remove the quotes, paste to join 2 consecutive lines together with a colon.

Upvotes: 3

Related Questions