繁体   English   中英

以相反的顺序连接文件

[英]Concat files in reverse order

我需要以相反的顺序将多个文件连接到一个文件。

不应更改文件中的行顺序。

例如:

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.txtls -r | xargs cat > 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 "%s\n" *.txt | tac | xargs -d'\n' cat

要完全反对文件名中的换行符,请使用零分隔流 - printf "%s\0" find.. -print0 xargs -0 tac -s ''

记住不要解析 ls

试试这个(递归)function:

function revcat
{
    (( $# == 0 )) && return 0
    revcat "${@:2}"
    cat -- "$1"
}

示例用法:

revcat *.txt

由于没有可以从 memory 轻松输入的简短的一行命令。 创建一个 function 并将其放入.bashrc文件是有意义的。

pjh 的递归 function工作缓慢。 所以我写了这个:

function revcat {
  for item in "$@"; do
    echo "$item"; 
  done | tac | xargs -d"\n" cat;
}

它像cat一样工作,但具有预期的、反向的文件连接顺序。

例如: revcat *.txt > out.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM