1

How can I use sed to replace second pattern found?

<default>...</default>
<default>...</default>
<default>...</default>

<setting id="lookandfeel.font" type="string" parent="lookandfeel.skin" label="13303" help="36107">
      <level>1</level>
      <default>Default</default>
</setting>

<default>...</default>
<default>...</default>
<default>...</default>

first pattern = lookandfeel.font

second pattern = Default

then replace "Default" with "Arial"

3 Answers3

2

With GNU sed:

sed '/<setting id="lookandfeel.font"/,/<\/setting>/{s|<default>Default</default>|<default>Arial</default>|}' file

If you want to edit "in place" add option -i.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
0

sed is for simple substitutions on individual lines, that is all. For anything even slightly more interesting you should be using awk for clarity, simplicity, robustness, portability, maintainability and almost every other desirable quality of software:

$ awk '/lookandfeel.font/{f=1} f&&sub(/Default/,"Arial"){f=0} 1' file
<default>...</default>
<default>...</default>
<default>...</default>

<setting id="lookandfeel.font" type="string" parent="lookandfeel.skin" label="13303" help="36107">
      <level>1</level>
      <default>Arial</default>
</setting>

<default>...</default>
<default>...</default>
<default>...</default>
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
-1

Consider this regex in Perl

s/(lookandfeel\.skin[\S\s]*)Default/$1Arial/gm

see: DEMO

According to this question and this question which tell that sed is difficult to handle pattern in multiple lines then I suggest you to use perl instead of sed.

Note If you want more strict regex please add more information into your question.

Community
  • 1
  • 1
fronthem
  • 4,011
  • 8
  • 34
  • 55
  • For `sed` you can access a parenthesized subexpression with `\1`, not `$1`. Consider checking your answer with sed. And the question doesn't concern the regex, it concerns matching a second pattern. – Andras Deak -- Слава Україні Aug 29 '15 at 11:06
  • I'm not familiar with `sed`, Please, give me some time. – fronthem Aug 29 '15 at 11:12
  • That's a bummer, since the question starts with "How can I use sed to replace second pattern found?" and the title and tags also include `sed`;) – Andras Deak -- Слава Україні Aug 29 '15 at 11:14
  • Nope at all, alternatively perl can done this and almost every machines have perl that's optional. – fronthem Aug 29 '15 at 11:15
  • 2
    the key point is to answer the question. the user has specified a tag/platform of bash and most environments that support bash will also support perl. so an answer in perl could be appropriate. but please post an answer that has practical value other than a theoretical regex pattern which only works online - remember all platforms have different standards for regex matching – amdixon Aug 29 '15 at 11:18