Search code examples
bashawksplitcut

split file into multiple files (by columns)


I have a file data.txt in which there are 200 columns and rows (a square matrix). So, i have been trying to split my file into 200 files, each of then with one of the column from the big data file. These where my two attempts employing cut and awk, however i don't understand why is not working.

NM=`awk 'NR==1{print NF-2}' < file.txt`
echo $NM

for (( i=1; i = $NM; i++ ))
do
echo $i 
cut -f ${i} file.txt > tmpgrid_0${i}.dat
#awk '{print '$i'}'  file.txt > tmpgrid_0${i}.dat
done

Any suggestions?.

EDIT: Thank you very much to all of you. All answers were valid but i cannot vote to all of them.


Solution

  • To summarise my comments, I suggest something like this (untested as I have no sample file):

    NM=$(awk 'NR==1{print NF-2}' file.txt)
    echo $NM
    
    for (( i=1; i <= $NM; i++ ))
    do
       echo $i 
       awk '{print $'$i'}'  file.txt > tmpgrid_0${i}.dat
    done