Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, sed, or awk one-liner to change the format of the file

I need advice on how to change the file formatted following way file1:

A       504688
B       jobnameA
A       504690
B       jobnameB
A       504691
B       jobnameC
...

into file2:

A       B
504688  jobnameA
504690  jobnameB
504691  jobnameC
...

One solution I could think of is:

cat file1 | perl -0777 -p -e 's/\s+B/\t/' | awk '{print $2"\t"$3}'.

But I am wondering if there is more efficient way or already known practice that does this job.

like image 769
Alby Avatar asked Dec 04 '22 17:12

Alby


2 Answers

 perl -nawe 'print "@F[1 .. $#F]", $F[0] eq "A" ? "\t" : "\n"' < /tmp/ab

Look up the options in perlrun.

Another useful one to add is -l (append newline to print), but not in this case.

like image 72
Lumi Avatar answered Mar 07 '23 16:03

Lumi


Assuming your input file is tab separated:

echo $'A\tB'
cut -f2 filename | paste - -

Should be pretty quick because this is exactly what cut and paste were written to do.

like image 35
glenn jackman Avatar answered Mar 07 '23 17:03

glenn jackman