4

I have a script bash that converts this file "origin.txt"

cxx-yyy-zzz-999-111
2018-01-1T00:10:54.412Z
2018-01-5T00:01:19.447Z
1111-6b54-eeee-rrrr-tttt
2018-01-1T00:41:38.867Z
2018-01-5T01:14:55.744Z
1234456-1233-6666-mmmm-12123
2018-01-1T00:12:37.152Z
2018-01-5T00:12:44.307Z

to

cxx-yyy-zzz-999-111,2018-01-1T00:10:54.412Z,2018-01-5T00:01:19.447Z
1111-6b54-eeee-rrrr-tttt,2018-01-1T00:41:38.867Z,2018-01-5T01:14:55.744Z
1234456-1233-6666-mmmm-12123,2018-01-1T00:12:37.152Z,2018-01-5T00:12:44.307Z

How could I do it in bash with AWK?

  • 4
    So what's the rule being applied here? if you just want to take lines 3 at a time I'd use something like paste -d, - - - < origin.txt or (if you insist on awk) awk '{ORS="\n"} NR%3 {ORS=","} 1' origin.txt – steeldriver Aug 6 '18 at 16:56
4

I have an awk script file named tmp.awk with the following contents

BEGIN {
   i=0
}
{
   if (i==0) {
      f1=$0
      i++
   } else if (i==1) {
      f2=$0
      i++
   } else {
      i=0
      print f1","f2","$0
   }
}

And a file origin.txt with the following contents

cxx-yyy-zzz-999-111
2018-01-1T00:10:54.412Z
2018-01-5T00:01:19.447Z
1111-6b54-eeee-rrrr-tttt
2018-01-1T00:41:38.867Z
2018-01-5T01:14:55.744Z
1234456-1233-6666-mmmm-12123
2018-01-1T00:12:37.152Z
2018-01-5T00:12:44.307Z

Here is my awk command and sample output.

zb@server ~ $ awk -f tmp.awk origin.txt 
cxx-yyy-zzz-999-111,2018-01-1T00:10:54.412Z,2018-01-5T00:01:19.447Z
1111-6b54-eeee-rrrr-tttt,2018-01-1T00:41:38.867Z,2018-01-5T01:14:55.744Z
1234456-1233-6666-mmmm-12123,2018-01-1T00:12:37.152Z,2018-01-5T00:12:44.307Z
  • thank you very much they gave me several ideas with their eternally grateful examples – kdetony Aug 7 '18 at 20:58
4

Using sed:

sed 'N;N;s/\n/,/g' origin.txt 

Using awk:

awk '{ printf "%s", $0; if (NR % 3 == 0) print ""; else printf "," }'  origin.txt 

Output:

cxx-yyy-zzz-999-111 2018-01-1T00:10:54.412Z 2018-01-5T00:01:19.447Z
1111-6b54-eeee-rrrr-tttt 2018-01-1T00:41:38.867Z 2018-01-5T01:14:55.744Z
1234456-1233-6666-mmmm-12123 2018-01-1T00:12:37.152Z 2018-01-5T00:12:44.307Z

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.