0

I have been asked to write a command that appends the n-th line (MYN) from a file (x)to another file (y). Here's what I've done so far:

MYN=4
hey=$(awk 'NR==$MYN' x)
echo "$hey" >> y 

But why doesn't this work?

Oli
  • 299,380
Martin Yeboah
  • 241
  • 4
  • 11

2 Answers2

2

I see your problem, you're using single quotes. They won't allow the Bash variable $MYN to expand. You can complicate things by telling awk a new variable, or because it's so simple, you can just switch to double-quotes:

awk "NR==$MYN" x

I'd have used sed but I can't see any obvious issues with your logic

MYN=4
sed "${MYN}q;d" x >> y

It seems to work as expected:

$ for i in $(seq 1 10); do echo $i >> x; done
$ sed "${MYN}q;d" x
4
Oli
  • 299,380
2

If your goal is to pass a variable to awk in order to use it within the script, you can use awk with the -v option:

hey=$(awk -v MYN=$MYN 'NR==MYN' x)
kos
  • 41,268