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:

    testfile3      <-No output because this file is empty

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


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?

  • Your example output does not match your first command line, but the second one.
    – Dubu
    Jan 19, 2016 at 13:32

3 Answers 3

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

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/' ./*
  • I tried to execute the first command in the terminal, but it does not work
    – Black
    Jan 19, 2016 at 13:24
  • 2
    @EdwardBlack "Does not work" is not a very helpful comment. Did you get an error message? Did you get the wrong output? I tried all four variants here and they all work for me.
    – Dubu
    Jan 19, 2016 at 13:30
  • I just get a ">" prompt where i have to enter something, the command is not complete as it seems
    – Black
    Jan 19, 2016 at 13:37
  • Entered one line at a time? The > is a secondary shell prompt. Jun 14, 2020 at 16:55
for f in *; do echo -e "$(cat $f)\t"$f; done 

I found a possible solution:

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

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.