1

I have a text file that contains entries shown below.

tag1start
text1
text2
text3
text4
tag1end
..
..
tag1start
text5
text6
text7
text8
tag1end

I need to change entries only in the first set of tag1start tag1end

I have attempted using "range" but it affects both the sets. How do I limit it only to the first set ?

/tag1start/,/tag1end/c\
Some other text1\
Some other text2\
Some other text3\
Some other text4\
Some other text5\
Some other text6\
tag1end
user1074593
  • 446
  • 1
  • 9
  • 23

2 Answers2

3
sed '/tag1end/,$!{1,/tag1start/!s/\(.*\)/Some other \1\\/;}'

Roughly translated: In all except the part from tag1end to the last line (which, being greedy, is everything after the first tag1end), do the following: in all except the part from line 1 to tag1start, turn foo into Some other foo\.

Beta
  • 96,650
  • 16
  • 149
  • 150
2

Consider:

$ sed '/tag1end/,${p;d}; /tag1start/,/tag1end/{s/^/Some other /}' file
Some other tag1start
Some other text1
Some other text2
Some other text3
Some other text4
tag1end
..
..
tag1start
text5
text6
text7
text8
tag1end

How it works

  • /tag1end/,${p;d}

    For all lines in the range from the first line matching tag1end to the end, $, print the line as it is (p) and start over with the next line (d).

  • /tag1start/,/tag1end/{s/^/Some other /}

    We only get to this command if we have not yet reached the first tag1end. If we have not yet reached tag1end and we are in the range /tag1start/,/tag1end/, then the commands in curly braces are performed. You can put whatever sed commands you like in those braces.

John1024
  • 109,961
  • 14
  • 137
  • 171