Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have text file similar to this:

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

I want to replace every "Keyword" with "number.extension" where number is 1 at first keyword match, 2 at second keyword match etc.

I know that I should use bash loop combined with sed (sed 's:Keyword:Number:g'), but I am not sure how to insert variable for number in that sed command.

As this is HTML file, there can be blank lines or any text beetween those "Keywords".

share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted

Does this do what you want?

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

For more complicated replacements (e.g. where maths is involved), more advanced scripting language might be more suitable.

share|improve this answer
    
Thanks, but it does not load any file and (as far as I can see) this is very important. Could you explain how it is supposed to work? –  Rafal Mar 11 '13 at 15:24
    
@Rafal: Just add the file path as the last argument, or redirect (pipe) it to the script. The -p switch loads the file automatically. –  choroba Mar 11 '13 at 15:38
    
Your orginal script does nothing with my file. I guess that I have not been clear about what I need. When I replace "Some-text" with ".*?" and second with "\1" reference it does change keyword to number of line. I have modified it, to do exactly what I need: 'perl -pe '$n++ if /MYLONGKEYWORD/; s/MYLONGKEYWORD/$n/' example-input.html'. Thank you for your help! –  Rafal Mar 12 '13 at 10:32
add comment

Edited : You may use the variable in sed as follows,

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
share|improve this answer
    
Thank you, but unfortunately, it does not do what I neeed. I have updated question to be more clear. This text beetween keywords might be very different. I just want to replace every occurence of my keyword with growing number and file extension. Example HTML files here dropbox.com/s/qinykn154nhjymu/example.zip –  Rafal Mar 11 '13 at 15:23
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.