1

Input file data

Name: aa
Age: 20
Address: zzzz

Name: bb
Age: 17
Address: cccc

I want to output like this

aa,20,zzzz
bb,17,cccc
  • welcome @Yumiko to Unix Stack overflow, to help us help you, please add a sample of your input file, I will try to edit your question based on my understandings, feel free to add your touch. – Eng7 Nov 8 '16 at 14:45
  • @Eng7 that is an example of the input file ;) – stevieb Nov 8 '16 at 14:46
2
$ cat ip.txt 
Name: aa
Age: 20
Address: zzzz

Name: bb
Age: 17
Address: cccc

$ awk 'NF{print $2}' ip.txt | pr -3ats,
aa,20,zzzz
bb,17,cccc
  • Using awk to print only second column values and skip empty lines by checking NF
  • Then use pr to print in 3 columns with , as separator
2
perl -00nE 'say join(",", /:\s*(.*)/g)' ip.txt

where:

  • perl -00nE EXP - stands for: foreach paragraph do {EXP}
  • /:(.*)/g - returns the list of the matching groups
  • join(",", list) - separate the elements by ,

\thanks{Sundeep}

  • good one, can use /:\s*(.*)/g to account for optional spaces between key-value pairs – Sundeep Nov 8 '16 at 16:00
1

An example using Perl. Iterate over each line in the file, and capture just the data we want into an array, then join the elements of the array with a comma and print it.

use warnings;
use strict;

my $file = 'file.txt';

open my $fh, '<', $file or die $!;

while (my $line = <$fh>){
    my @sections = $line =~ /:\s(.*?)\s/g;
    print join ',', @sections;
    print "\n";
}

Output:

aa,20,zzzz
bb,17,cccc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.