Coding di ikkoyeah

Sometimes it happens that we don’t have much memory in our device, so we have to give to some base command of the linux shell. For example, if we have to use the shell sh, we don’t have the basic command paste, that allows to merge together the cloumn of two or more files.  In this post we will see how-to build the equivalent function paste in awk language.

First of all we create a file called paste.awk and we write on it these instructions:

FILENAME == ARGV[1] { one[FNR]=$1 }
FILENAME == ARGV[2] { two[FNR]=$1 }
FILENAME == ARGV[3] { three[FNR]=$1 }
FILENAME == ARGV[4] { four[FNR]=$1 }
FILENAME == ARGV[5] { five[FNR]=$1 }

    for (i=1; i<=length(one); i++) {
        print one[i], two[i], three[i], four[i], five[i]

As you can see, in this example we took as parameter (from the shell) 5 files. If you have to use less/more files, you have to remove/add one/more row/s “FlLENAME”.

Finally to run the script we have to launch this command in the shell and it will save the result on the file “result”:

awk -f paste.awk file1  file2  file3   file4   file5 > result