使用bash脚本检查一个文件是否多次附加到另一个文件的最佳方式是什么?我需要在不安装额外工具的情况下执行此操作我正在通过追加另一个文件来定期更新文件,并希望确保该操作以前没有发生过。防止多次附加到文件
我试过做各种差异和wc解决方案,但找不到解决方案。
使用bash脚本检查一个文件是否多次附加到另一个文件的最佳方式是什么?我需要在不安装额外工具的情况下执行此操作我正在通过追加另一个文件来定期更新文件,并希望确保该操作以前没有发生过。防止多次附加到文件
我试过做各种差异和wc解决方案,但找不到解决方案。
正如mklement0所示,一个解决方案可能是将目标文件的源文件的最后一行写到diff
,源文件中的行数与源文件的行数相同。这里是一个草图:
#!/bin/bash
# USAGE: append_uniq.sh target source
# append source to target only if last part of target != source
target_file=$1
source_file=$2
source_num_lines=$(wc -l < "$source_file")
diff_target_lines=$(tail -n $source_num_lines "$target_file")
if ! diff "$source_file" <(echo "$diff_target_lines") > /dev/null; then
echo "Appending $source_file to $target_file"
cat "$source_file" >> "$target_file"
else
echo "Already appended, skipping"
fi
奖励:一个班轮
附加文件a
到文件lines
除非a
已于去年追加到lines
。两个文件都必须存在:
! diff -q a <(tail -n $(wc -l < a) lines) && cat a >> lines
当您追加时,是否可以插入包含可帮助您做出该决定的信息的分界线?具体来说,您是如何尝试(并失败)检查的? – mklement0
diff a.csv b.csv | sed -e'1d'-e's /^..// g'| diff - a.csv | sed -e'1d'-e's /^..// g'| diff - b.csv是一种方法。 $ 1,$ 2作为文件参数 L1 = $(diff $ 1 $ 2 | sed -e'1d'-e's /^..// g'| wc -l | awk'{print $ 1}') L2 = $(wc -l $ 2 | awk'{print $ 1}') L3 = $(wc -l $ 1 | awk'{print $ 1}') if [$(($ L1 + $ L3))-ne $ L2]; 然后 回声“$ 1上的比较失败” \t exit 1; fi 是另一个。 该文件是为其他系统读取的,因此添加分隔线会很困难。我对我可怜的bash脚本编写技巧感到抱歉 – SMC
请将代码片段放在'\''(反引号)中 - 这使得它们更容易阅读。你的片段看起来非常复杂 - 一般来说,下面的方法会起作用吗?从参考文件所在目标文件的末尾提取多行,然后将提取的行与参考文件进行比较。 – mklement0