1

I have a tab separated file file.txt whose contents are as follows :

word11 word12 word13 word14
word21 word22 word23 word24
word31 word32 word33 word34
word41 word42 word43 word44

I want to copy each column in a different file. For example: First file will have contain :

word11
word21
word31
word41

Second file will contain:

word12
word22
word32
word42

I wrote the script for the same (There are 12 columns):

for i in {1..12}
do
        awk -F "\t" '{print $i}' file.txt > /tmp/output-$i.txt
done

But all output files contain all the data:

word11 word12 word13 word14
word21 word22 word23 word24
word31 word32 word33 word34
word41 word42 word43 word44

Thanks for the help.

Inian
  • 80,270
  • 14
  • 142
  • 161
AkaSh
  • 486
  • 4
  • 16
  • you could just use cut – JoshKisb Dec 28 '17 at 11:56
  • Awk doesn't know about the shell variable `$i` so it evaluates to empty, hence your print statement is simply `print`, which prints the whole line. See here: https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script – jas Dec 28 '17 at 11:56

2 Answers2

5

You are trying to use shell variables in Awk which would never work. But what you are trying to do can be done totally in Awk itself. The for loop upto NF will parse all your columns, you don't need to hard-code it anymore.

awk -v FS="\t" '{for (i=1;i<=NF;i++) print $i > ("/tmp/output-"i);}'  file.txt
Inian
  • 80,270
  • 14
  • 142
  • 161
3

You could instead just use cut

for i in {1..12}
do
    cut -f$i file.txt > /tmp/output-$i.txt;
done
JoshKisb
  • 742
  • 7
  • 9