2014-01-28 76 views
3

使用bash腳本檢查一個文件是否多次附加到另一個文件的最佳方式是什麼?我需要在不安裝額外工具的情況下執行此操作我正在通過追加另一個文件來定期更新文件,並希望確保該操作以前沒有發生過。防止多次附加到文件

我試過做各種差異和wc解決方案,但找不到解決方案。

+0

當您追加時,是否可以插入包含可幫助您做出該決定的信息的分界線?具體來說,您是如何嘗試(並失敗)檢查的? – mklement0

+0

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

+0

請將代碼片段放在'​​\''(反引號)中 - 這使得它們更容易閱讀。你的片段看起來非常複雜 - 一般來說,下面的方法會起作用嗎?從參考文件所在目標文件的末尾提取多行,然後將提取的行與參考文件進行比較。 – mklement0

回答

3

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

只是一個建議:你可能會考慮'$(wc -l <​​a)'替代管道'$(wc -l a | cut -d''-f1)' – John1024

+0

@ John1024 - 太好了,謝謝!爲單行 – grebneke

+0

+1,但請對所有對「$ source_file」和「$ target_file」的引用重複引號。 – BMW