bash 스크립트의 sed 명령에 변수 삽입

bash 스크립트의 sed 명령에 변수 삽입

다음과 유사한 텍스트 파일이 있습니다.

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

모든 "키워드"를 "number.extension"으로 바꾸고 싶습니다. 여기서 숫자는 첫 번째 키워드 일치에서는 1이고 두 번째 키워드 일치에서는 2입니다.

sed(sed 's:Keyword:Number:g')와 결합된 bash 루프를 사용해야 한다는 것을 알고 있지만 해당 sed 명령에 숫자에 대한 변수를 삽입하는 방법을 잘 모르겠습니다.

이 파일은 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'\''/'

보다 복잡한 대체(예: 수학이 관련된 경우)의 경우 고급 스크립트 언어가 더 적합할 수 있습니다.

관련 정보