1

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?

  • Your example output does not match your first command line, but the second one. – Dubu Jan 19 '16 at 13:32
5
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:

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

Or to avoid printing the name of empty files:

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
-1

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.