[Solved] Assigning a value to a variable name then running a loop on these values

Hi, I was wondering if anyone could assist me for (what is probably) a very straightforward answer.

I have input files containing something like

File 1

Apples
Apples
Apples 
Apples

File 2 

Bananas
Bananas 
Bananas
Bananas 

etc

I want to add a second column where the same number is equal to each fruit e.g. and these need to be sequential (ie, file 1, column 2 value = 1, file 2, column 2 value = 2) etc. The output files would look like this:

File 1

Apples 1
Apples 1 
Apples 1 
Apples 1

File 2 

Bananas 2
Bananas 2
Bananas 2
Bananas 2

File 3 

Pears 3
Pears 3
Pears 3
Pears 3

I can write the loop for the different fruits easily enough, the problem is adding 1 to the column in each subsequent file. I tried using awk to print values into the second column directly:

awk '{(($2=1))}1' apples.txt > apples_with_1_in_second_column.txt

This works fine for running individual fruits. Unfortunately, this is a small example and I have hundreds of different files like this and it would take ages to do each one individually.

I was thinking something like:

fruit=(apples bananas pears) 
for i in {0..2}
do
awk '{$2=(Value + 1 for each subsequent file}1' ${fruit[$i]}.txt > ${fruit[$i]}_with_number_in_second_column.txt
done

Can anyone suggest a generic script that would allow me to do this for hundreds of files like the one above? I'm not married to a solution using awk and any assistance would be very much appreciated.

Like this..?

awk 'FNR==1 {i++} {print $0 FS i > FILENAME"_with_"i}' apples bananas pears

Hi, thanks for your rapid response. I changed the code a little because it kept throwing up syntax errors.

fruit=(apples bananas)
for i in {0..1} 
do
awk 'FNR==1 {i++} {print $0 FS i}' ${fruit[$i]}.txt > ${fruit[$i]}_$i.txt
done

It is creating the output files, but 1 is in the second column for both apples and bananas, rather than 1 for apples and 2 for bananas. Am I missing something obvious?

Thanks!

The "i" variable in my post is the awk variable and has nothing to do the shell (for loop). If you have files-names in an array, you can use like this

awk 'FNR==1 {i++} {print $0 FS i > FILENAME"_with_"i}' ${fruit[*]}

Just try this command (without using loop).

---------- Post updated at 23:24 ---------- Previous update was at 23:11 ----------

with loop,

for i in {0..1} 
do
awk -v i=$(( i+1 )) '{print $0 FS i}' ${fruit[$i]}.txt > ${fruit[$i]}_$i.txt
done

Again, both the i's are different. just like this

for i in {0..1} 
do
awk -v x=$(( i+1 )) '{print $0 FS x}' ${fruit[$i]}.txt > ${fruit[$i]}_$i.txt
done

But, In this case you must know the number of elements of the array (right?)
You better loop over the files rather than index.

1 Like

Sorry for the slow reply back. Brilliant that has solved it. Many thanks for your help CLX :slight_smile: