0

I use this to put all names of the ".txt" files into a file:

find . -name "*.txt" | sort > txtfile

How to display all the first 20 lines (if less than 20, supplied with blank lines) for all the files that are listed in txtfile?

1

As the filenames are newline separated in the file txtfile, you can read each file, check if the number of lines is equal to (or greater than 20), if so print the first 20 lines, else print newlines for the remaining lines:

while IFS= read -r f; do 
    lines=$(wc -l <"$f")
    if (( lines < 20 )); then
        cat -- "$f" 
        for ((i=20; i>lines; i--)); do 
            echo
        done
    else 
        head -20 -- "$f"
    fi
done <txtfile
  • 1
    I removed my previous comment. But maybe simple concatenation will be faster? Simply create file containing 20 empty lines and do (head -qn 20 $file 20empty_lines.txt) | head -qn 20 – Kalavan Sep 20 '16 at 8:10
0

If you have an awk that supports the ENDFILE rule, you could do

xargs -a txtfile awk 'FNR <= 20 {print} ENDFILE {for (n=FNR+1;n<=20;n++) print ""}'

If you don't mind having a header for each file, you could use pr to print the first 20-line 'page' of each file

xargs -a txtfile pr +1:1 -l25

(Unfortunately although pr has an option to suppress the header, that option also suppresses the pagination). If you do mind the headers, then you could process the files individually and remove them using tail e.g.

while read -r f; do 
  pr +1:1 -l25 "$f" | tail -n +6
done < txtfile

or (with GNU sed's 'n skip m' addressing)

xargs -a txtfile pr +1:1 -l25 | sed '1~25,+4d'

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.