每五个 .txt 文件合并功能

每五个 .txt 文件合并功能

我有一个问题,我的文件夹包含 1500 个 .txt 文件。我需要编写一个函数将每五个合并为一个。现在我这样做:

cat 1.txt 2.txt 3.txt 4.txt 5.txt >> 1a.txt

但是改变数字需要很长时间,你有什么功能可以让我更快吗?

答案1

# Set the nullglob shell option to make globbing patterns
# expand to nothing if pattern does not match existing
# files (instead of remaining unexpanded).
shopt -s nullglob

# Get list of files into list of positional parameters.
# Avoid the files matching "*a.txt".
set -- *[!a].txt

# Concatenate five files at a time for as long as
# there are five or more files in the list.
while [ "$#" -ge 5 ]; do
    cat "$1" "$2" "$3" "$4" "$5" >"${n}a.txt"

    n=$(( n + 1 ))
    shift 5
done

# Handle any last files if number of files
# was not a factor of five.
if [ "$#" -gt 0 ]; then
    cat "$@" >"${n}a.txt"
fi

这会在循环中进行串联,一次五个文件,以输出名为 等的文件1a.txt2a.txt它不假设这些文件具有除文件名后缀之外的特殊名称.txt,但代码将避免文件匹配,*a.txt因为这些文件是输出文件。

答案2

假设您的文件按顺序编号:

for i in {1..1500..5}; do
  cat "$i.txt" "$((i+1)).txt" "$((i+2)).txt" "$((i+3)).txt" "$((i+4)).txt" > "${i}a.txt"
done

这使用大括号扩展生成基值,以及算术展开计算剩余值。

相关内容