Matilde
Matilde

Reputation: 363

LINUX awk loop through several lines of a txt file

I need to loop through several rows of a text file and redirect to another text file.

I managed to do the following:

for i in $(seq 1 24)
awk 'NR==1 {print $4 $5 $6}'  3dfwhmx.txt > values.txt
values='cat*values.txt'
3dClust -fwhmxyz ${values}
done

However this only address the first row, 4,5,6th column. I would need to use the i index in order to address the 1st, 2nd, 3rd etc row. I do need to create a vector of values for each iteration of i.

I tried several things eg;

awk 'NR=='$i'  {print $4 $5 $6}'  3dfwhmx.txt > values.txt

but it does not work. I would really appreciate any feedback on this!

Upvotes: 0

Views: 5625

Answers (2)

P.P
P.P

Reputation: 121387

You don't need a loop around awk.

awk 'NR<=24{print $4}'  3dfwhmx.txt > values.txt

will get you the first 24 lines as your logic with loop does.


With the updated question, you don't need a temporary file either.

for i in $(seq 1 24); do
   values=$(awk -v i=$i 'NR==i {print $4 $5 $6}'  3dfwhmx.txt)
   3dClust -fwhmxyz ${values}
done

Depending on how 3dClust works, you might be able to simple redirect `awk's output to its stdin using a pipe.

Upvotes: 0

Ian Kenney
Ian Kenney

Reputation: 6426

do you need to loop through it and call awk for each line?

Why not just

awk '{print $4}'  3dfwhmx.txt > values.txt

or change your quotes to allow the shell substitution

awk "NR==$i {print $4}"  3dfwhmx.txt > values.txt

Upvotes: 1

Related Questions