I would like to replace the first character C with H for 23 lines (say, lines 83 to 106) after every interval of 82 lines. How can I do this using sed or awk?

  • 1
    awk allows you to select line numbers based on a formula, e.g. the pattern NR%82>0 && NR%82<=23 selects your lines (there might be a need for fine-tuning the formula). To replace the first C, the sub function should be appropriate. I don't know if sed has that much flexibility for line selection. – berndbausch Mar 2 at 9:18
  • 3
    Can you provide an example of the input with associate desired output? It sometimes helps to understand border cases. Also, please indicate what you already tried and where you ran into problems. – AdminBee Mar 2 at 10:15

Generate a sample file

lines=$(( $lines_per_set * $sets ))
  yes CC | head -n "$lines" |  nl > file

Initialize two counters and downcount them. The outer counter reset triggers re initialisation.

awk '
  !k       {j= 24; k= 82}
  j && j-- {sub(/C/,"H")}
' file

Same idea as above in GNU sed where the counters are held in the hold space.

sed -En '
' file

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