[英]Merge files with same name in different folders
我是 Linux 新手,我正在尋找一個命令來合並具有相同名稱但來自不同文件夾的文件。 像這樣:
folder 1, folder l1
folder 1 contains folder 2 and files 1.txt, 2.txt, 3.txt, ...
folder 2 contains files 1.txt, 2.txt, 3.txt, ...
我想合並文件夾 1 和子文件夾 2 中的兩個文本,然后將它們放入文件夾 l1。
我懂了:
ls ./1 | while read FILE; do
cat ./1/"$FILE" ./1/2/"$FILE" >> ./l1/"$FILE"
done
這個似乎運行良好,合並了兩個文件,但是,在文件夾 l1 中創建了一個新的空文件 2,並在 shell 上創建了兩條警告消息: cat: ./1/2: Is a directory cat: ./1/2 /2: 沒有那個文件或目錄
我想知道新文件 2 和警告消息的解釋,更重要的是如何改進命令行或新解決方案,因為我有幾十個文件夾 1。
你的代碼看起來很不錯。 它發出警告,因為您也在嘗試合並目錄! 您可以添加檢查以跳過目錄,如下面的代碼:
#!/bin/bash
cd 'folder 1'
for file in *.txt; do
[[ ! -f $file ]] && continue # pick up only regular files
otherfile="folder 2/$file"
[[ ! -f $otherfile ]] && continue # skip if there is no matching file in folder 2
cat "$file" "$otherfile" > "folder l1/$file.merged"
done
引用上述變量以防止分詞很重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.