3

I have text file input.txt in each of the hundred subfolders named sample_1, ..., sample_100.

I can extract first line of all input.txt files using below command:

find -name input.txt -exec awk 'FNR == 1 {print $0}' > out.txt {} \;

But this prints the first line of all input.txt to one out.txt file in the current directory.

What I want is out.txt in each subfolder with first line of input.txt in that particular subfolder. For example, out.txt inside sample_57 subfolder will have first line of input.txt in sample_57.

Any idea on how to get this done.

4

Just do

find . -type f -name "input.txt" -execdir awk 'NR==1{print $0>"out.txt"}' '{}' +

Or you can use exit handler, which it will exit after print first line and better when you only want to print first line and not required awk to process whole file till the end of it.

find . -type f -execdir awk '{print $0>"out.txt";exit}' '{}' +
7

Use head instead of awk. Also, use -execdir instead of -exec to make the command to execute easier to read.

find -type f -name input.txt -execdir sh -c 'head -1 input.txt > out.txt' \;
5

out.txt in each subfolder with first line of input.txt in that particular subfolder

find + sed solution:

find . -type f -name input.txt -exec sh -c 'out_fn="${1%/*}/out.txt"; sed -n "1p" "{}" > "$out_fn"' _ {} \;
  • out_fn="${1%/*}/out.txt" - path to output filename in format /path/to/subfolder/out.txt

  • sed -n "1p" "{}" - extracts the 1st line from the input file {}

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.