I want to change a text file that contains for example :
a 1
b 2
a 3
b 4
to:
a b
1 2
3 4
any idea how I can accomplish that? I am not familiar with awk but I think it is the way to go?
Advertisement
Answer
I’m assuming the input is always two columns, the first column contains the column headers of the output repeated over and over, and that the output may contain one or more columns.
$ cat t.awk { sep = (FNR % n == 0) ? "n" : " " } NR==FNR { printf $1 sep; if (sep == "n") nextfile; next; } { printf $2 sep }
The number of output columns is set with -v
when invoking awk. Note also
that the input file needs to be provided twice on the command line as the
script does a quick initial pass to print out the output column headers
before starting over to print the data (too lazy to deal with arrays).
Two-column output:
$ cat file.txt a 1 b 2 a 3 b 4 a 5 b 6 $ awk -v n=2 -f t.awk file.txt file.txt a b 1 2 3 4 5 6
Three-column output:
$ cat file2.txt a 1 b 2 c 3 a X b Y c Z a @ b # c $ $ awk -v n=3 -f t.awk file2.txt file2.txt a b c 1 2 3 X Y Z @ # $