0

I want to print every 88th line of a file (merged.txt) into a new file, but I want the code to do this starting on every number 1 to 88 and make 88 files

current script:

for Y in {1..88}
do
awk  'NR % 88 == $Y'  merged.txt  > atom_$Y.txt
done

when I run this I get the error code:

illegal field $(), name "Y"
 input record number 1, file merged.txt
 source line number 1
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 3
    See [How do I use shell variables in an awk script?](https://stackoverflow.com/questions/19075671/how-to-use-shell-variables-in-an-awk-script) but I'd suggest to do everything within awk itself, no need bash loop – Sundeep Aug 04 '20 at 14:59
  • Here's an example that you can adapt: `seq 10 | awk 'NR % 2{f = "atom_" ++c ".txt"; print > f; close(f)}'` or perhaps you wanted something like `seq 10 | awk '{f = "atom_" (NR%3) ".txt"; print >> f; close(f)}'` – Sundeep Aug 04 '20 at 15:01
  • `awk -v n=88 '{ y=NR%n; print >"atom_"(y?y:n)".txt" }' merged.txt` – jhnc Aug 04 '20 at 15:08
  • 1
    If you are calling `awk` inside a loop, your are probably doing it wrong. – M. Nejat Aydin Aug 04 '20 at 20:24

1 Answers1

0

Here is my solution:

awk '{print > "atom_" (NR % 88)}' merged.txt

This will create the atom_0, atom_1, ... files. For more information about redirection in awk, look it up here

Update

I studied your solution and found the reason it does not work is because of this expression: 'NR % 88 == $Y': The $Y variable is not expanded. That means you should place it outside of the single quote like this: 'NR % 88 =='%Y

Update 2

I found Claire's solution does not create an atom_0, but atom_88 file. However, atom_88 is empty. It should work if she adjust the loop to for Y in {0..87}

Hai Vu
  • 37,849
  • 11
  • 66
  • 93