0

I have lines in file:

Desktop DELL firewall UP CPU 20core configured 
Desktop HP firewall DOWN CPU 18core unconfigured

I want to first match UP and then if next line match DOWN replace these two lines with some string

I tried

perl -p -e 's?.*firewall.*UP.*\n.*firewall.*DOWN.*?STRG?' file

but it doesnt work

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
kunal
  • 35
  • 2
  • Possible duplicate: [How to replace multiple any-character (including newline) in Perl RegEx?](https://stackoverflow.com/q/36533282/2173773) – Håkon Hægland Aug 12 '17 at 13:51

2 Answers2

2

/\n.*f/ can't possibly match since you are reading newline-terminated lines one at a time.

A convenient trick is to use -0777 to load the entire file into memory at once.

perl -0777pe's/^.*firewall.*UP.*\n.*firewall.*DOWN.*/STRG/m' file
ikegami
  • 367,544
  • 15
  • 269
  • 518
1

With sed:

sed '/firewall.*UP/{N;/firewall[^\n]*DOWN/s/.*/somestr/}' file

details:

/firewall.*UP/ {      # condition
    N;                # append the next line to the pattern space
    /firewall[^\n]*DOWN/  # condition
        s/.*/somestr/ # then: replace all with somestr
}
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • Might this create a false positive if `DOWN` was in the same line as `UP`? – potong Aug 12 '17 at 11:22
  • @potong: clearly yes, but I doubt this can happen. However I will replace the second `.*` with `[^\n]*` to be sure that *firewall* and *DOWN* are on the same line (the second one). – Casimir et Hippolyte Aug 12 '17 at 12:01