说我想将file_b.txt
的内容附加到file_a.txt
。但仅当file_a.txt
尚未包含file_b.txt
的内容时。我如何首先在第一个文件中搜索第二个文件的内容?
所以给定file_a.txt
:
the quick
brown fox
和file_b.txt
:
jumped over
the lazy
dog
和script.sh
的开头:
#!/bin/bash
# make sure file_b.txt isn't already in file_a.txt, then:
cat file_b.txt >> file_a.txt
无论执行script.sh
多少次,我怎样才能确保我最终得到这个?
the quick
brown fox
jumped over
the lazy
dog
答案 0 :(得分:0)
也许你可以试试diff
,就像这样。
#!/bin/sh
diff <(tail -$(wc -l file_b.txt | awk '{print $1}') file_a.txt) file_b.txt
is_appended=$?
if is_appended ; then
exit 1; # file_b.txt has been appended.
else
cat file_b.txt >> file_a.txt
fi
exit 0
答案 1 :(得分:0)
你可以做一个嵌套的while循环来实现所需的结果
#!/usr/bin/env bash
isNotReadInFile=0;
while read secondFile;do
while read firstFile;do
[[ "${firstFile}" != "${secondFile}" ]] && {
isNotReadInFile=1;
}
done < ./file_a.txt
(( isNotReadInFile == 1 )) && {
echo "${secondFile}" >> ./file_a.txt;
isNotReadInFile=0;
}
done < ./file_b.txt
答案 2 :(得分:0)
与:bash text search: find if the content of one file exists in another file中的建议相似 你可以用
grep -q -f file_a.txt file_b.txt
全文
editor cat_if_not_already_there.sh
粘贴
#!/bin/bash
file1=$1
file2=$2
if grep -q -f $file1 $file2 ;
then
cat $file1 # already contains the text
else
cat $file1 $file2 # ok concat
fi
制作可执行文件
chmod u+x cat_if_not_already_there.sh
准备测试文件
echo -e "the quick\nbrown fox" >file_a.txt
echo -e "jumped over\nthe lazy\ndog" >file_b.txt
cat file_a.txt file_b.txt > file_c.txt
期待cat
被执行
./cat_if_not_already_there.sh file_a.txt file_b.txt
the quick
brown fox
jumped over
the lazy
dog
[OK]
预计cat
不会被执行
./cat_if_not_already_there.sh file_c.txt file_b.txt
the quick
brown fox
jumped over
the lazy
dog
[OK]
向观众提问
./cat_if_not_already_there.sh file_c.txt file_a.txt
表现如预期吗? ./cat_if_not_already_there.sh file_b.txt file_b.txt
表现如预期吗? ./cat_if_not_already_there.sh file_a.txt file_c.txt
表现如预期吗?