2

I have a folder called PKA1

Within this folder I have several folders named as:

1eV, 2eV .... 30eV

Within each of these subfolders I have a file called PKA.dump

I want to copy the 20th line of PKA.dump in each subfolder to a file called data.txt.

I know I can use the find command to find all PKA.dump files as:

find . -type f -name PKA.dump

I also know I can write individually with sed:

sed -i '20q;d' PKA.dump > data.txt

But when I try to loop through all files and use sed such as:

find . -type f -name PKA.dump | sed -i '20q;d' PKA.dump > data.txt

I get this error:

sed: can't read PKA.dump: No such file or directory

Any help? I just want to sequentially have the 20th line from PKA.dump in file 1eV, 2eV, 3eV etc in a file called data.txt.

3
find . -name PKA.dump -type f -exec awk '
   FNR == 20 {print; nextfile}' {} +

nextfile, where available (GNU awk and some others like FreeBSD's and recent versions of mawk and soon to be added to the standard) will skip to the next file. Where not, it will be ignored (it's just like dereferencing a nextfile variable); it will still work but read the files fully.

You can still do:

find . -name PKA.dump -type f -exec sed '20q;d' {} \;

But that means running one sed command per file which would be less efficient.

  • When I do: find . -name PKA.dump -type f -exec awk ' FNR == 20 {print; nextfile}' {} +nextfile I get an error find: missing argument to `-exec' – Jackson Hart Apr 4 '15 at 16:38
  • @j you've got a spurious nextfile next to your + – Stéphane Chazelas Apr 4 '15 at 16:54
  • where is this file saved? I do not see it in directory? – Jackson Hart Apr 4 '15 at 17:35
  • @JacksonHart - it's not in your directory, you entered it in terminal at the end of your command (the command ends with a +, nothing should follow). Copy>paste the exact command in Stéphane's answer and it will work. – don_crissti Apr 4 '15 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.