Bash
每五個 .txt 文件合併的功能
我有一個問題,我的文件夾包含 1500 個 .txt 文件。我需要編寫一個函式來將每五個合併為一個。現在我這樣做:
cat 1.txt 2.txt 3.txt 4.txt 5.txt >> 1a.txt
但是更改數字需要很長時間,您有什麼功能可以讓我更快嗎?
假設您的文件按順序編號:
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
# 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.txt
,2a.txt
等等。它不假定文件具有除.txt
文件名後綴之外的特殊名稱,但程式碼將避免文件匹配*a.txt
,因為這些是輸出文件。