Bash Shell脚本:以递归方式将文件夹中的TXT文件分类

时间:2019-01-09 20:58:39

标签: bash shell unix command-line

我有一个文件目录,其结构如下:

./DIR01/2019-01-01/Log.txt
./DIR01/2019-01-01/Log.txt.1
./DIR01/2019-01-02/Log.txt
./DIR01/2019-01-03/Log.txt
./DIR01/2019-01-03/Log.txt.1
...
./DIR02/2019-01-01/Log.txt
./DIR02/2019-01-01/Log.txt.1
...
./DIR03/2019-01-01/Log.txt

...等等。 每个DIRxx目录都有许多按日期命名的子目录,它们本身具有许多需要连接的日志文件。要连接的文本文件的数量各不相同,但理论上可以多达5个。我希望看到在带日期的目录中为每个文件集执行以下命令(请注意,文件必须以相反的顺序连接):

cd ./DIR01/2019-01-01/
cat Log.txt.4 Log.txt.3 Log.txt.2 Log.txt.1 Log.txt > ../../Log.txt_2019-01-01_DIR01.txt

(我理解上面的命令将给出某些文件不存在的错误,但是无论如何cat都会满足我的需要) 除了cd进入每个目录并运行上面的cat命令之外,如何将其编写为Bash shell脚本?

2 个答案:

答案 0 :(得分:0)

If you just want to concatenate all files in all subdirectories whose name starts with Log.txt, you could do something like this:

for dir in DIR*/*; do 
    date=${dir##*/}; 
    dirname=${dir%%/*}; 
    cat $dir/Log.txt* > Log.txt_"${date}"_"${dirname}".txt; 
done

If you need the files in reverse numerical order, from 5 to 1 and then Log.txt, you can do this:

for dir in DIR*/*; do 
    date=${dir##*/}; 
    dirname=${dir%%/*}; 
    cat $dir/Log.txt.{5..1} $dir/Log.txt > Log.txt_"${date}"_"${dirname}".txt; 
done

That will, as you mention in your question, complain for files that don't exist, but that's just a warning. If you don't want to see that, you can redirect error output (although that might cause you to miss legitimate error messages as well):

for dir in DIR*/*; do 
    date=${dir##*/}; 
    dirname=${dir%%/*}; 
    cat $dir/Log.txt.{5..1} $dir/Log.txt > Log.txt_"${date}"_"${dirname}".txt; 
done 2>/dev/null

答案 1 :(得分:0)

不如其他全面,但快速简便。使用findsort输出,但是您喜欢(-zrn--zero-terminated --reverse的输出,然后使用--numeric-sort对其进行迭代。

read