我有兩個檔案和一個 shell 腳本。
文件一:
Batman
Superman
John Snow
Jack Sparrow
Rob Stark
文件2:
Batman
Ironman
Superman
Spiderman
John Snow
Arya Stark
Jack Sparrow
Rob Stark
The hound
腳本:
#!/bin/bash
sort ~/Desktop/file1.txt > ~/Desktop/fileA.txt
sort ~/Desktop/file2.txt > ~/Desktop/fileB.txt
diff -y ~/Desktop/fileA.txt ~/Desktop/fileB.txt > ~/Desktop/diff.txt
該腳本運行得非常好,輸出是:
> Arya Stark
Batman Batman
> Ironman
Jack Sparrow Jack Sparrow
John Snow John Snow
Rob Stark Rob Stark
> Spiderman
Superman Superman
> The hound
但我想自動輸出為:
File A File B
> Arya Stark
Batman Batman
> Ironman
Jack Sparrow Jack Sparrow
John Snow John Snow
Rob Stark Rob Stark
> Spiderman
Superman Superman
> The hound
僅使用 diff 命令的最佳方法是什麼?
答案1
您可以對您的方法進行各種改進,但是,保持所有內容相同,您所需要做的就是在腳本中再添加一行,然後將最後一行追加 ( >>
) 而不是覆蓋:
#!/bin/bash
echo -e "FileA\t\t\t\t\t\t\t\tFileB" > diff.txt
sort ~/Desktop/file1.txt > ~/Desktop/fileA.txt
sort ~/Desktop/file2.txt > ~/Desktop/fileB.txt
diff -y ~/Desktop/fileA.txt ~/Desktop/fileB.txt >> ~/Desktop/diff.txt
更好的寫法是
#!/usr/bin/env bash
file1="$1"
file2="$2"
printf "%-36s%36s\n" "FileA" "FileB"
diff -y <(sort "$file1") <(sort "$file2")
然後運行:
script.sh file1.txt file2.txt > diff.txt
這可以避免創建不必要的臨時文件,並且不需要將文件名稱硬編碼到腳本中。
或者,如果您希望顯示實際的檔案名,請將printf
上面的呼叫變更為
printf "%-36s%36s\n" "$file1" "$file2"