I have a file like this...1562 first part1563 H     col3 H col41564 H     col3 H col4...3241 H     col3 H col43242 third part...I want to replace only the first H in every line to H#, with # is its number of appearance. The output should be:...1562 first part1563 H1    col3 H col41564 H2    col3 H col4...3241 H1652 col3 H col43242 third part...So far, I've tried:max=`grep -c ' H ' b`while [[ $i -le $max ]];do  grep -m $i ' H ' b|tail -n1|sed s/H/H$i/1  let i=i+1doneThis code is slow, it needs to read every line to replace and can't add the first part and third part of the file. Is there any better way to do this? Maybe awk? Thank you.
How to replace all the first occurences in matched lines with incremental number?
shell script;text processing;awk;replace
You can for example use this:$ awk '/H/{sub(H, H++v)}1' file1562 first part1563 H1     col3 H col41564 H2     col3 H col43241 H3     col3 H col43242 third part...This looks for those lines containing H and replaces that H with H together with a variable we keep incrementing. Note you could use gsub() instead of sub() if you wanted to perform this change in all the matched patterns instead in just one.The final 1 is a true condition, hence it performs the default awk action: {print $0}, that is, prints the full line.