Shell – Cat all files in a folder including filename by using a for loop

catshell-scripttext processing

With this for loop which I execute directly in the shell, I am able to cat the contents of all files in a folder, with the value beside of it:

$ for f in *; do echo -e "\t"$f"\n"; cat $f; done

Example output:

100 
    testfile1
    testfile3      <-No output because this file is empty
hello 
    testfile2

But I'd like to print the value on the right side and the file on the top left like this:

testfile1 
    100
testfile3
testfile2
    hello

I tried to swap the position of echo and cat but that doesn't work, it works exactly as the other command.

$ for f in *; cat $f; do echo -e "\t"$f"\n"; done

How can I achieve this?

Best Answer

for f in *; do
  printf '%s\n' "$f"
  paste /dev/null - < "$f"
done

Would print the file name followed by its content with each line preceded by a TAB character for each file in the directory.

Same with GNU awk:

gawk 'BEGINFILE{print FILENAME};{print "\t" $0}' ./*

Or to avoid printing the name of empty files (this one not GNU specific):

awk 'FNR==1 {print FILENAME}; {print "\t" $0}' ./*

Or with GNU sed:

sed -s '1F;s/^/\t/' ./*
Related Question