Shell脚本合并文本文件
有时候,要遇到将多个文件合并成一个的需要,除了重复的复制和粘贴,还可以通过Shell来辅助实现。下面是两种实现方案。
1、写一个Shell脚本
这里通过运行merge.sh可以将同目录下的所有的txt文件合并到all.all。
merge.sh:
ls *.txt |
while read file_name;
do
# 用.为分隔符只要文件名,去掉文件后缀
echo "${file_name%.*}:" >> all.txt
cat "$file_name" >> all.txt
echo "" >> all.txt
done
效果如下:

2、cat命令
上面的方法中,需要写一个Shell脚本,有些麻烦。其实,可以直接通过cat命令来实现。
默认地,cat命令可以直接接收多个参数,这样,通过重定向可以很方便地合并文件:

但是,如果想在各个文件内容的前面加一些说明,就像前面的shell脚本一样,就需要利用cat命令的一个小feature。下面是man cat中的描述:
The cat utility reads files sequentially, writing them to the standard output. The file operands are processed in command-line order. If file
is a single dash (`-') or absent, cat reads from the standard input.
如果cat接收的文件名参数为“-”或者没有,cat命令就从标准输入读取内容。
利用这一点,我们可以在文件参数之间间隔加入“-”。这样,每当读取完一个文件的内容,cat都会从标准输入读取下一个文件的说明信息。结束输入的时候,我们需要按Ctrl+d输入EOF,来结束标准输入读取。如下:

3、附
前面的脚本中用到了shell字符串变量的截取,在下面补充下截取方法说明:
{varible#string}从左向右截取第一个string后的字符串
{varible%string}从右向左截取第一个string后的字符串
“*”只是一个通配符可以不要
From: https://blog.csdn.net/lizhidefengzi/article/details/76762059