我有两个文件和一个 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"