0

How to call the output file as the string in 4th column of output (or according to 4th column of ith row of the input)?

I tried:

for i in {1..321}; do
awk '(FNR==i) {outfile = $4 print $0 >> outfile}' RV1_phase;
done

or

for i in {1..321}; do
awk '(FNR==i) {outfile = $4; print $0}' RV1_phase > "$outfile";
done

input file:

1 2 2 a
4 5 6 f
4 4 5 f
....
....

desired input i=1 name: a

1 2 2 a

The aim: I have data that I plotted in gnuplot and I would like to plot set of figures named after string to know which point come from which file. The point will be coloured. I need to get files for plotting in gnuplot so I would like to create them using the cycle from my question.

Alex
  • 347
  • 1
  • 10
  • On first look, it looks to me you are looking for how to pass bash/shell variable to awk. Your question is not that clear, could you please do add more details in your question and let us know then, as its not clear as of now. – RavinderSingh13 Apr 01 '20 at 12:36

1 Answers1

2

Simply

for i in {1..321}; do
awk '(FNR==i) {print $0 >> $4}' RV1_phase;
done

The problem with your first attempt was that you didn't use a ; to separate the assignment to outfile from the print command. The separate variable isn't necessary, though.

You don't need a bash loop, either:

awk '1 <= FNR && FNR <= 321 {print $0 >> $4}' RV1_phase;
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    `FNR==i` won't work though. `i` is not imported in `awk`'s context. It can't live in two possible worlds ;) – Inian Apr 01 '20 at 12:43
  • 2
    That would fail saying "too many open files" once you get past about a dozen output files unless you're using GNU awk. In that case you'd need to close() the output files as you go. – Ed Morton Apr 01 '20 at 13:34