1

separate columns of a text file

Hii experts i have a big text file that contain many columns.Now i want to extract each column in separate text file serially with adding two strings on the top.

suppose i have a input file like this

2 3 4 5 6 
3 4 5 6 7
2 3 4 5 6
1 2 2 2 2

then i need to extract each column in separate text file with two strings on the top

file1.txt      file2.txt     .... filen.txt

s=5            s=5
r=9            r=9
2              3
3              4
2              3
1              2

i tried script as below:but it doesnot work properly.need help from experts.Thanks in advance.

#!/bin/sh
for i in $(seq 1 1 5)

do
echo $i
awk '{print $i}' inp_file  > file_$i
done

Submitted November 26th 2020 by Admin

Answers
0

Could you please try following, written and tested with shown samples in GNU awk. Following doesn't have close file function used because your sample shows you have only 5 columns in Input_file. Also created 2 awk variables which will be printed before actual column values are getting printed to output file(named var1 and var2).

awk -v var1="s=5" -v var2="r=9" '
{ count++ for(i=1;i<=NF;i++){ outputFile="file"i".txt" if(count==1){ print (var1 ORS var2) > (outputFile) } print $i > (outputFile) }
}
' Input_file

In case you can have more than 5 or more columns then better close output files kin backend using close option, use this then(to avoid error too many files opened).

awk -v var1="s=5" -v var2="r=9" '
{ count++ for(i=1;i<=NF;i++){ outputFile="file"i".txt" if(count==1){ print (var1 ORS var2) > (outputFile) } print $i >> (outputFile) } close(outputFile)
}
' Input_file

Admin | 10 months ago


0

Pretty simple to do in one pass through the file with awk using its output redirection:

awk 'NR==1 { for (n = 1; n <= NF; n++) print "s=5\nr=9" > "file_" n } { for (n = 1; n <= NF; n++) print $n > "file_" n }' inp_file

Admin | 10 months ago



Relevant Questions