使用“cat”命令时显示文件名及其内容

使用“cat”命令时显示文件名及其内容

cat用于显示文件内容时是否有命令显示目录或文件名?

例如:假设有两个文件f1.txt并且f2.txt位于./tmp

./tmp/f1.txt
./tmp/f2.txt 

然后,当我这样做时cat ./tmp/*.txt,只会显示文件的内容。但如何先显示文件名,然后显示内容呢?例如:

 (The needed command):
 ./tmp/f1.txt:  
 This is from f1.txt
 and so on
 ./tmp/f2.txt:
 This is from f2.txt ...

有命令可以做到吗? (似乎没有cat显示文件名的选项。)

答案1

就像另一个想法一样,尝试一下tail -n +1 ./tmp/*.txt

==> ./tmp/file1.txt <==
<contents of file1.txt>

==> ./tmp/file2.txt <==
<contents of file2.txt>

==> ./tmp/file3.txt <==
<contents of file3.txt>

答案2

$ for file in ./tmp/*.txt; do printf '%s\n' "$file";  cat "$file"; done

-或者-

$ find ./tmp -maxdepth 1 -name "*.txt" -print -exec cat "{}" \;

答案3

不完全符合您的要求,但您可以每行前缀与文件名:

$ grep '^' ./tmp/*.txt
./tmp/f1.txt: this is from f1.txt
./tmp/f1.txt: blaa, blaa, blaa...
./tmp/f1.txt: blaa, blaa, blaa...
./tmp/f2.txt: this is from f2.txt
./tmp/f2.txt: blaa, blaa, blaa...
./tmp/f2.txt: blaa, blaa, blaa...

如果不借助一些脚本,很难做得比这更好。

答案4

您可以轻松地编写一个小脚本来执行此操作,

for f in "$@" do; echo "This is from $f"; cat -- "$f"; done

相关内容