Riddly
Riddly

Reputation: 19

awk in a for loop to make multiple files named after each line of another file

I am trying to use awk in a for loop to take 2 different columns everytime from one file and write them into multiple files. Plus, these files should be named after the each line of another file.

File_A

Jan  Z  H  T  K  L  A
Feb  Q  V  H  G  E  T
Mar  W  O  P  J  K  L
Apr  N  M  B  V  C  X

I want to create multiple text files taking column1(months)+column2 from File_A for the first time and column1+column3 for the second and column1+column4 for the third and so on.

File_B

2010
2011
2012
2013
2014
2015

Then, name these files with each row from File_B (file_2010.txt, file_2011.txt, ...).

I tried to do it like this, but it does not write the files.

for L in {2010..2015}; do awk '{print $1'\t'$2}' File_A.txt > file_{L}.txt; done

Thanks for any solution!

Upvotes: 0

Views: 61

Answers (1)

karakfa
karakfa

Reputation: 67507

awk to the rescue! (note that there is no validation)

$ awk 'NR==FNR {a[NR]=$1; next} 
               {for(i=2;i<=NF;i++) print $1,$i > a[i-1]}' fileB fileA

$ head 201?
==> 2010 <==
Jan Z
Feb Q
Mar W
Apr N

==> 2011 <==
Jan H
Feb V
Mar O
Apr M

==> 2012 <==
Jan T
Feb H
Mar P
Apr B

==> 2013 <==
Jan K
Feb G
Mar J
Apr V

==> 2014 <==
Jan L
Feb E
Mar K
Apr C

==> 2015 <==
Jan A
Feb T
Mar L
Apr X

or, without the years file, if they are consecutive

$ awk -v start=2010 '{for(i=2;i<=NF;i++) print $1,$i > (start+i-2)}' fileA

for tab delimited output insert -v OFS='\t' before the script.

Upvotes: 2

Related Questions