It is getting extremely old producing a new script for each output order you want. Let's try a configurable script. Feed it a configuration file that contains one line for each output section you want to create where each line contains a space separated list of the field numbers you want to print in the section corresponding to the line number in the configuration file and then give it the name of the file you want to extract fields from for the first output section, the name of the file you want to extract fields from for the second output section, etc., with one input file for each line in the configuration file:
#!/bin/ksh
printf '%s\n' "1 2" 3 "6 5 4" | awk '
FNR == 1 {
fc++
}
fc == 1 {
# Read fields to be included in each segment of hte output.
for(i = 1; i <= NF; i++)
osfo[NR + 1, i] = $i
osc[NR + 1] = NF
next
}
{ for(i = 1; i <= osc[fc]; i++)
printf("%s%s", $osfo[fc, i], i == osc[fc] ? ORS : OFS)
}' - file file file
In this example we create a configuration file (using the printf
command in a pipeline and specify the input file name -
to read it from standard input) to print fields 1 and 2 in the first output section; field 3 in the second output section; and fields 6, 5, and 4 (in that order) in the third output section. Since the 3 input files in this example all have the same name, we'll be extracting fields from the same file. If the file named file
contains:
1 2 3 a b c
3 4 5 c d e
7 8 9 f g h
(as in one of your many examples), the output will be:
1 2
3 4
7 8
3
5
9
c b a
e d c
h g f
If you want to change the output field separators for various sections, you can specify that in the list of files. For example, if you change the last line to:
}' - OFS="," file file OFS="|" file
the output will be:
1,2
3,4
7,8
3
5
9
c|b|a
e|d|c
h|g|f
Will this meet your many and varied requirements?