3

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?

Black
  • 2,079

3 Answers3

9
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/' ./*
  • I tried to execute the first command in the terminal, but it does not work – Black Jan 19 '16 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 '16 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 '16 at 13:37
  • Entered one line at a time? The > is a secondary shell prompt. – Paul_Pedant Jun 14 '20 at 16:55
0
for f in *; do echo -e "$(cat $f)\t"$f; done 
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
-1

I found a possible solution:

for f in *; do echo -e $f"\n\t$(cat $f)"; done
Black
  • 2,079