【问题标题】:Preventing multiple appends to a file防止多次附加到文件
【发布时间】:2014-02-19 06:05:34
【问题描述】:

使用 bash 脚本检查一个文件是否多次附加到另一个文件的最佳方法是什么?我需要在不安装额外工具的情况下执行此操作。我通过向文件附加另一个文件来定期更新文件,并希望确保该操作以前没有发生过。

我尝试过各种 diff 和 wc 解决方案,但找不到解决方案。

【问题讨论】:

  • 追加时,是否可以插入一条分界线,其中包含可以帮助您做出决定的信息?具体来说,您之前是否尝试过(但失败了)检查?
  • diff a.csv b.csv | sed -e '1d' -e 's/^..//g' |差异 - 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 上的差异失败”退出 1; fi 是另一个。该文件是为其他系统读取的,因此很难添加分隔线。我为我糟糕的 bash 脚本技能道歉
  • 请在`(反引号)中附上代码sn-ps - 这使它们更容易阅读。您的 sn-ps 看起来非常复杂 - 一般来说,以下方法可行吗?从目标文件末尾提取与参考文件一样多的行,然后将提取的行与参考文件进行比较。

标签: bash file append


【解决方案1】:

正如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

【讨论】:

  • 只是一个建议:您可以考虑将$(wc -l &lt;a) 替换为管道$(wc -l a | cut -d' ' -f1)
  • +1,但请双引号引用所有对 $source_file$target_file 的引用。
  • 我用过DIFF=$(diff $1 $2) if [ -s $1 ] &amp;&amp; [ -s $2 ] &amp;&amp; [ "$DIFF" != "" ]; then L1=$(diff $1 $2 | sed -e '1d' -e 's/^..//g' | diff - $2 | sed -e '1d' -e 's/^..//g' | grep -xc "-") if [[ $L1 -ne 1 ]]; then echo "Failed diff on $1" exit 1; fi fi
猜你喜欢
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多