Sign up ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

I have text file similar to this:


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

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

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

cp yourfile tempfile
for (( i=1; i<=`wc yourfile | awk '{ print $1 }'`; i++))

#for (( j=1; j<=`sed -n ''"$i"' p' yourfile | wc | awk '{ print $2 }'`; j++))
        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 ]
        count=$(expr $count + 1)
        cp yourfile tempfile
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 – Rafal Mar 11 '13 at 15:23

Your Answer


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.