0

Am i doing something wrong?

This loop doesn't seem to work.

#!/usr/bin/ksh

num=3
for i in $(seq 1 "$num") 
do
awk 'NR==$i' "$file1" > "$file2"
# Doing some operation
done

I want 3 awk to be executed:

awk 'NR==1' "$file1" > "$file2"
# do some operation
awk 'NR==2' "$file1" > "$file2"
# do some operation
awk 'NR==3' "$file1" > "$file2"
# do some operation
Novice_Techie
  • 426
  • 3
  • 10
  • 21

1 Answers1

2

In Bourne shell and its derivatives (ksh, zsh, etc.), variables are not expanded inside single quotes.

Change:

awk 'NR==$i'

to:

awk "NR==$i"

If your awk program is longer that this single line, keep the single quotes and define an awk variable with -v:

awk -v "i=$i" 'NR == i'
xhienne
  • 5,738
  • 1
  • 15
  • 34
  • If my actual awk is awk 'NR==$i && $0 ~ /^apple/ {print > "file2"}' file1 then i need to modify to awk -v "i=$i" 'NR == i && $0 ~ /^apple/ {print > "file2"}' file1 – Novice_Techie Aug 07 '20 at 00:35
  • Exactly, else `$0` will be substituted by the shell – xhienne Aug 07 '20 at 00:37
  • @EdMorton Sorry if my (deleted) comment sounded aggressive. Here is a summary -- hope you won't find it offending: `sed -n "$n p"` and `awk "NR == $n"` are commonly used in the real world to print the Nth line. As long as you keep them that short, there is nothing wrong about them (they can be optimized though). Moreover, my answer ends by suggesting `awk -v`, which appears to match your own suggestion and which was chosen by the OP. Since you rarely downvote without proposing a better more educative answer, where is it? I'd like to see that "completely unnecessary" loop removed. – xhienne Aug 07 '20 at 23:13
  • @EdMorton OK, so `awk "NR == $n"` is a vector of attacks and the commonly used `sed -n "$n p"` looks perfectly safe to you (you never heard of sed's `w` command or GNU sed's `e` and `s///e` then?). OK, so you do not ever, ever post an answer on a question that has an accepted answer. OK, so you downvote without any explanation, which is highly educative for the poster AND for the OP that accepted the answer. OK, OP are required to illustrate their issue with a specially crafted minimal example but when they do, you complain that the code doesn't make sense. Ite missa est. – xhienne Aug 08 '20 at 09:32