This question already has answers here:
Why should there be a space after '[' and before ']' in Bash?
(4个答案)
How to compare number of lines of two files using Awk
(2个答案)
2年前关闭。
我想比较两个单独文件的行数。在比较中尝试使用
我有:
但是,if / then语句未返回正确的输出。
如果文件1和2的行数相同,那么编写此代码的正确方法是什么?
File1.txt:
File2.txt:
更新:我们发现
上面的代码示例:
假设我们有以下Input_files:
现在,由于我们可以看到两个文件中的行数不相等,因此将得出以下结果。
现在,如果我们使文件的两行相等,如下所示。
现在,当我们运行相同的代码时,它将给出以下内容。
(4个答案)
How to compare number of lines of two files using Awk
(2个答案)
2年前关闭。
我想比较两个单独文件的行数。在比较中尝试使用
wc -l
时,我正在努力使其正常工作。我有:
if [ "$(wc -l file1.txt)" == "$(wc -l file2.txt)" ]; then echo "Warning: No Match!"; fi
但是,if / then语句未返回正确的输出。
如果文件1和2的行数相同,那么编写此代码的正确方法是什么?
File1.txt:
example1
example2
example3
File2.txt:
example4
example5
example6
更新:我们发现
wc -l
命令必须只为比较返回一个数字。与问题Why should there be a space after '[' and before ']' in Bash?不同,此问题需要使用wc -l
来获得一个可以比较单独文件中的行数的整数。 最佳答案
您能否尝试遵循并让我知道这是否对您有帮助。
if [ "$(wc -l < file1.txt)" -eq "$(wc -l < file2.txt)" ]; then echo 'Match!'; else echo 'Warning: No Match!'; fi
上面的代码示例:
假设我们有以下Input_files:
cat file1.txt
I
am
Cookie
cat file2.txt
I
am
Cookie
现在,由于我们可以看到两个文件中的行数不相等,因此将得出以下结果。
if [ "$(wc -l < file1.txt)" -eq "$(wc -l < file2.txt)" ]; then echo 'Match!'; else echo 'Warning: No Match!'; fi
Warning: No Match!
现在,如果我们使文件的两行相等,如下所示。
cat file1.txt
I
am
Cookie
cat file2.txt
I
am
Cookie
现在,当我们运行相同的代码时,它将给出以下内容。
if [ "$(wc -l < file1.txt)" -eq "$(wc -l < file2.txt)" ]; then echo 'Match!'; else echo 'Warning: No Match!'; fi
Match!