0

here is my program:

for ((i=1;i<=300;i++)); do

  awk 'NR==$i{print}' file.dat > fileB.dat

done

the file.dat contains 300 lines that I want to save in different files, but the NR==$i doesn't work, nothing is printed.

I don't see what is wrong. Thank you

1
  • Sorry I am confused: Do you want to generate a single file with one line or 300 files with different lines? Commented Nov 29, 2013 at 14:06

2 Answers 2

4

Single quotes prevent expansion, so $i is not expanded into a number. Use double quotes instead.

However, instead of invoking awk multiple times in a loop, it's more efficient to use a single awk like this:

awk 'NR<=300 {print > NR".dat"}' file.dat

This will write each line to a different file.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the right answer but it needs to be print > (NR".dat") as it's ambiguous without the parens.
2

Try:

for i in {1..300}; do
    awk "NR==$i{print}" file.dat > fileB.dat
done

The single quote ', prevents the shell from expanding variables, in this case i.

2 Comments

@EdMorton - well, dogbanes answer is much better, I just saw the error as a quoting issue and didn't think about it too much (I guess that's why he's a 70k rep user :-)
The error is not a quoting issue though, it's a thinking error in mistaking awk for shell. By changing the quoting you can force the $i to expand but then you open yourself up to backslash hell because then $1 wouldn't mean the 1st field in the current record any more it'd mean the first positional parameter in the shell command so then you'd need to write \$1 just to get the normal, expected awk functionality. To get the value of a shell variable inside an awk script, you use -v i="$i" or similar. There are other awk problems introduced too and yes, the shell loop is wrong too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.