我想在Linux中编写一个shell脚本,循环遍历所有目录和子目录,并对所有文本文件进行一次cat。下面是我到目前为止得到的,我在这个逻辑上有点落后。有人可以帮帮我吗?谢谢
该脚本采用 1 个参数,例如:./script.sh directoryName
#!/bin/bash
echo "Directory $1"
cd $1
for f in *.txt
do
cat $f
done
我不确定如何从这里进入子目录,因为每个子目录中可能有无限数量。
Use find
.
If your operating system supports a modern version of POSIX:
find "$1" -type f -name '*.txt' -exec cat '{}' +
...or, if it doesn't:
find "$1" -type f -name '*.txt' -exec cat '{}' ';'
...or, if you want to be inefficient (or have a more interesting use case you haven't told us about), and your find
supports -print0
...
find "$1" -type f -name '*.txt' -print0 | \
while IFS='' read -r -d '' filename; do
cat "$filename"
done
Don't leave out the -print0
-- otherwise, maliciously-named files (with newlines in their names) can inject arbitrary names into your stream (at worst), or hide from processing (at best).
find . -name '*.txt' -print0 | xargs -0 cat
如果需要特定目录,请将 替换为目录.
的完整路径。find
获取以扩展名结尾的文件.txt
并将其通过管道传输到在它们上xargs
运行命令的cat
文件。-0
选项xargs
按字面意思接受输入。-print0
模式适合这个...
您可以使用find
或递归。
使用递归的示例:
dump_files()
{
for f in $1/*; do
if [[ -f $f ]]; then
cat $f
elif [[ -d $f ]]; then
dump_files $f
fi
done
}
改变循环
for f in $(find . -name *.txt);do
cat $f
done