Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to output data from multiple files in side by side columns in one file via awk?

I have 30 files, called UE1.dat, UE2.dat .... with 4 columns in every of them. An example of their column structure is given below for UE1.dat and UE2.dat.

UE1.dat

1 4 2 1 
2 2 3 3
3 2 4 4   
4 4 4 2

UE2.dat

2 6 8 7 
4 4 9 6
7 1 1 2   
9 3 3 3

So, i have tried with the following code:

for((i=1;i<=30;i++)); do awk 'NR$i {printf $1",";next} 1; END {print ""}' UE$i.dat; done > UE_all.dat

to get only the first column from every file and write them in a single file and columns to be side by side,The desired OUTPUT is given below.

1 2
2 4
3 7
4 9

But unfortunately, the code orders them in rows, can you give a hint?

Thank you in advance!

like image 296
Trifon Getsov Avatar asked Dec 13 '25 06:12

Trifon Getsov


1 Answers

In awk you can do it this way:

1) Put this code in a file named output_data_from_multiple_files.awk:

BEGIN {
    # All the input files are processed in one run.
    # filenumber counts the number of input files.
    filenumber = 1
}

{
    # FNR is the input record number in the current input file.
    # Concatenate the value of the first column in the corresponding
    # line in the output.
    output[FNR] = output[FNR] " " $1

    # FNR == 1 means we are processing a new file.
    if (FNR == 1) {
        ++filenumber
    }
}

END {
    # print the output
    for (i=1; i<=FNR; i++)
        printf("%s\n", output[i])
}

2) Run awk -f output_data_from_multiple_files.awk UE*

All the files are handled in a single execution of awk. FNR is the input record number in the current input file. filenumber is used to count the number of processed files. The values read in the input files are concatenated in the output array.

like image 50
Xebax Avatar answered Dec 16 '25 05:12

Xebax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!