我想将多个文本文件连接到终端中的一个大文件。我知道我可以使用cat命令来做到这一点。但是,我希望每个文件的文件名在该文件的“数据转储”之前。有人知道怎么做吗?

我目前拥有的:

file1.txt = bluemoongoodbeer

file2.txt = awesomepossum

file3.txt = hownowbrowncow

cat file1.txt file2.txt file3.txt

期望的输出:

file1

bluemoongoodbeer

file2

awesomepossum

file3

hownowbrowncow

当前回答

如果你想要的结果与你想要的输出格式相同,你可以尝试:

for file in `ls file{1..3}.txt`; \
do echo $file | cut -d '.' -f 1; \ 
cat $file  ; done;

结果:

file1
bluemoongoodbeer
file2
awesomepossum
file3
hownowbrowncow

你可以在剪切之前和之后加上echo -e,这样你就有了行与行之间的间距:

$ for file in `ls file{1..3}.txt`; do echo $file | cut -d '.' -f 1; echo -e; cat $file; echo -e  ; done;

结果:

file1

bluemoongoodbeer

file2

awesomepossum

file3

hownowbrowncow

其他回答

find . -type f -print0 | xargs -0 -I % sh -c 'echo %; cat %'

这将打印完整的文件名(包括路径),然后是文件的内容。它也非常灵活,因为您可以为find命令使用name“expr”,并在文件上运行任意多的命令。

如果你想要的结果与你想要的输出格式相同,你可以尝试:

for file in `ls file{1..3}.txt`; \
do echo $file | cut -d '.' -f 1; \ 
cat $file  ; done;

结果:

file1
bluemoongoodbeer
file2
awesomepossum
file3
hownowbrowncow

你可以在剪切之前和之后加上echo -e,这样你就有了行与行之间的间距:

$ for file in `ls file{1..3}.txt`; do echo $file | cut -d '.' -f 1; echo -e; cat $file; echo -e  ; done;

结果:

file1

bluemoongoodbeer

file2

awesomepossum

file3

hownowbrowncow

这也可以做到:

$ find . -type f -print -exec cat {} \;
./file1.txt
Content of file1.txt
./file2.txt
Content of file2.txt

下面是对命令行参数的解释:

find    = linux `find` command finds filenames, see `man find` for more info
.       = in current directory
-type f = only files, not directories
-print  = show found file
-exec   = additionally execute another linux command
cat     = linux `cat` command, see `man cat`, displays file contents
{}      = placeholder for the currently found filename
\;      = tell `find` command that it ends now here

您还可以通过布尔运算符组合搜索,如-and或-or。找到-ls也很好。

find . -type f -exec cat {} \; -print

这个方法将先打印文件名,再打印文件内容:

tail -f file1.txt file2.txt

输出:

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

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