For my homework, I have to check if two files in a directory have the same contents and if so, replace one with a hardlink to the other. My script looks like:
对于我的作业,我必须检查目录中的两个文件是否具有相同的内容,如果是,请用另一个硬链接替换另一个。我的脚本看起来像:
cd $1 # $1 is the directory this script executes in
FILES=`find . -type f`
for line1 in $FILES
do
for line2 in $FILES
do
(check the two files with cmp)
done
done
My problem is that I can not figure out the conditional expression to make sure that the two files are not the same: If the directory has files a,b,c, and d it should not return true for checking a against a. How do I do this?
我的问题是我无法弄清楚条件表达式以确保两个文件不相同:如果目录有文件a,b,c和d,则不应该返回true来检查a。我该怎么做呢?
Edit: So I've got this:
编辑:所以我有这个:
cmp $line1 $line2 > /dev/null
if [ $? -eq 0 -a "$line1" != "$line2" ]
But it counts the files twice: It checks a
and b
, and then b
and a
. for some reason, using <
with strings does not work.
但它会对文件进行两次计数:它检查a和b,然后检查b和a。出于某种原因,使用
Edit: I think I figured it out, the solution is to use a \
before the <
编辑:我想我弄清楚了,解决方案是在 <之前使用\< p>
2 个解决方案
#1
1
Using test
, or its alias [
:
使用test或其别名[:
if [ "$line1" < "$line2" ]
then
check the files
fi
Note that I'm using <
here instead of !=
(which would otherwise work) so that, once you've compared a
with b
, you won't later compare b
with a
.
请注意,我正在使用
#2
0
Here is an optimized way to do it that also properly handle files with embedded spaces or similar:
以下是一种优化的方法,可以正确处理带有嵌入空格或类似内容的文件:
find . -type f -exec sh -c '
compare() {
first=$1
shift
for i do
cmp -s "$first" "$i" || printf " %s and %s differ\n" "$first" "$i"
done
}
while [ $# -gt 1 ]; do
compare "$@"
shift
done ' sh {} +
#1
1
Using test
, or its alias [
:
使用test或其别名[:
if [ "$line1" < "$line2" ]
then
check the files
fi
Note that I'm using <
here instead of !=
(which would otherwise work) so that, once you've compared a
with b
, you won't later compare b
with a
.
请注意,我正在使用
#2
0
Here is an optimized way to do it that also properly handle files with embedded spaces or similar:
以下是一种优化的方法,可以正确处理带有嵌入空格或类似内容的文件:
find . -type f -exec sh -c '
compare() {
first=$1
shift
for i do
cmp -s "$first" "$i" || printf " %s and %s differ\n" "$first" "$i"
done
}
while [ $# -gt 1 ]; do
compare "$@"
shift
done ' sh {} +