在 bash 腳本中將變數插入到 sed 指令中

在 bash 腳本中將變數插入到 sed 指令中

我有與此類似的文本文件:

Some-text
Keyword
Some-text
Some-text
Keyword
Some-text
Keyword
Keyword

我想用“number.extension”替換每個“關鍵字”,其中第一個關鍵字匹配時的數字為 1,第二個關鍵字匹配的數字為 2 等。

我知道我應該將 bash 循環與 sed (sed 's:Keyword:Number:g') 結合使用,但我不確定如何在 sed 命令中插入 number 變數。

由於這是 HTML 文件,因此這些「關鍵字」之間可以有空行或任何文字。

答案1

編輯:您可以在 sed 中使用該變量,如下所示,

count=1
extension=".jpg"
cp yourfile tempfile
for (( i=1; i<=`wc yourfile | awk '{ print $1 }'`; i++))
do

#for (( j=1; j<=`sed -n ''"$i"' p' yourfile | wc | awk '{ print $2 }'`; j++))
#do
        sed -i ''"$i"' s/[a-zA-Z0-9]*[Kk][Ee][Yy][Ww][Oo][Rr][Dd]/'"$count$extension"'/1' yourfile
        diff yourfile tempfile
        if [ $? -ne 0 ]
        then    
        count=$(expr $count + 1)
        cp yourfile tempfile
        fi  
#done
done

答案2

這是你想要的嗎?

perl -pe '$n++ if /Some-text/;s/Keyword/SomeText '\''$n'\''/'

對於更複雜的替換(例如涉及數學的情況),更高級的腳本語言可能更合適。

相關內容