Home > Net >  Converting a list of strings into a single line with sed/awk on linux
Converting a list of strings into a single line with sed/awk on linux

Time:01-14

I have a file say test.txt, which contains data as list of values/strings and also have some empty lines in between as shown below

Val1
Val2
Val3

Val4
Val5

Val6


Required output :
Val1, Val2, Val3
Val4, Val5
Val6


I am using below command, but it's returning all the available values in single line. But I want only consecutive values should concat together(comma seperated) and a new line should start whenever it hits an empty line (there can me more than one consecutive empty lines).

cat test.txt | sed 's/<[^>]*>//g' | sed 's/ //g' | sed 's/.*/&/;$!s/$/, /' | tr -d '\n'

CodePudding user response:

I think this is what you're trying to do, using any awk:

$ awk -v RS= -F'\n' -v OFS=', ' '{$1=$1} 1' test.txt
Val1, Val2, Val3
Val4, Val5
Val6

CodePudding user response:

Try this one:

   awk '{if(NF){if(!line)line=$0;else line=line", "$0;}else{print line;line=""}}END{print line}' test.txt

Output:

Val1, Val2, Val3
Val4, Val5
Val6

CodePudding user response:

With gnu-sed you can read the whole file with -z

Capture 2 non newlines in 2 capture groups surrounding a single newline, and in the replacement use 2 backreferences with , in between

Then replace 2 or more newlines with a single newline.

sed -Ez 's/([^\n])\n([^\n])/\1, \2/g;s/\n{2,}/\n/g' file

Output

Val1, Val2, Val3
Val4, Val5
Val6

Using only sed -E you can accomplish the same using a label reading all lines:

sed -E ':a;$!{N;ba};s/([^\n])\n([^\n])/\1, \2/g;s/\n{2,}/\n/g' file

CodePudding user response:

If ed is available/acceptable.

ed -s file.txt <<-'EOF'
  ,$-1g/.\{1,\}/;/^$/-s/$/, /
  ,$-1g/.\{1,\}/;/^$/j
  %s/, *$//
  %p
  Q
EOF
  • Related