我需要以相反的顺序将多个文件连接到一个文件中。
文件中的行顺序不应更改。
例如:
file 1.txt
1
2
file 2.txt
3
4
预期结果:
result.txt
3
4
1
2
这些命令无法按预期工作:
tac *.txt > result.txt
只是颠倒文件中行的顺序,并按顺序连接文件。(2 1 4 3
(
如果文件名具有空格字符,则cat $(ls -r) > result.txt
或ls -r | xargs cat > result.txt
不起作用:
cat: file: No such file or directory
cat: 2.txt: No such file or directory
cat: file: No such file or directory
cat: 1.txt: No such file or directory
问题是,虽然ls -r
返回'file 2.txt' 'file 1.txt'
,但echo $(ls -r)
返回的file 2.txt file 1.txt
看起来像是cat
的四个文件。
太好了,所以首先列出文件名,然后颠倒它们的顺序,然后将它们分类。
find . -type f -name '*.txt' | sort -r | xargs -d'n' cat
与文件名扩展类似,它是按自身排序的:
printf "%sn" *.txt | tac | xargs -d'n' cat
若要对文件名中的换行符进行完整显示,请使用零分隔流-printf "%s "
find .. -print0
xargs -0
tac -s ''
。
记住不要解析ls.
试试这个(递归(函数:
function revcat
{
(( $# == 0 )) && return 0
revcat "${@:2}"
cat -- "$1"
}
示例用法:
revcat *.txt
因为没有一个短的单行命令可以很容易地从内存中键入。创建一个函数并将其放入.bashrc
文件中是有意义的。
pjh的递归函数运行速度慢得不合适。所以我写了这个:
function revcat {
for item in "$@"; do
echo "$item";
done | tac | xargs -d"n" cat;
}
它的工作方式与cat
类似,但具有预期的反向文件连接顺序。
例如:revcat *.txt > out.txt
。