Search code examples
bashloopsif-statementcat

Need to iterate over all the items in my current directory and print their names along with other operations


I need to create a loop that will iterate over all the items in my current directory to check whether this item is file, then print the name of the file and the 1st 10 lines of the file.

I did the following:

for f in *;do if [ -f "$f" ];then echo "$f" | cat $f | head -n 10;fi;done >output.txt

this code extracts 10 lines from each file but does not print the file name first.

So, I need to save the output as printed filename first, followed by the first 10 lines from it.


Solution

  • Solved by this code:

    for f in *;do if [ -f "$f" ];then echo "$f"; cat $f | head -n 10 $f; echo "---------------";fi;done >hello.txt