replacing a string contained withing two strings with an incremental counter in bash

$ awk '/^>.*#/{sub(/^>[^#]+/, ">model_" ++c)} 1' ip.txt
>model_1#Dakota
text
text
text
>model_2#Idao
text
text
text
>model_3#Alabama
text
text
text
>model_4#Dakota
text
text
text
>model_5#Honduras
text
text
text
  • /^>.*#/ if line starts with > and has # in the line
  • sub function helps to search and replace first match
  • /^>[^#]+/ match characters from start of line from > until just before # character
  • ">model_" ++c replacement string
    • c will be zero at the start (since this is numerical context), ++c will give the value after incrementing, so first time we get 1, next time 2 and so on

$ awk 'sub(/^>[^#]+/,""){$0=">model1_" (++cnt) $0} 1' file
>model1_1#Dakota
text
text
text
>model1_2#Idao
text
text
text
>model1_3#Alabama
text
text
text
>model1_4#Dakota
text
text
text
>model1_5#Honduras
text
text
text

Could you please try following too.

awk 'match($0,/>.*#/){print ">model_"++count"#" substr($0,RSTART+RLENGTH);next} 1' Input_file

Tags:

Text

Awk

Sed