问题描述:

I have this file:

a

b

c

d

## Mainteinance Page

# RewriteEngine On

# RewriteCond %{REQUEST_URI} !^/courtesy-page.html$

# RewriteRule .* https://%{HTTP_HOST}/courtesy-page.html [R]

e

f

g

h

I want to remove the # from lines where the sed command matches this string:

!^/courtesy-page.html$

and also the lines preceding and following the matching line.

expected results:

a

b

c

d

## Mainteinance Page

RewriteEngine On

RewriteCond %{REQUEST_URI} !^/courtesy-page.html$

RewriteRule .* https://%{HTTP_HOST}/courtesy-page.html [R]

e

f

g

h

How can I write this expression?

网友答案:

Using awk:

$ cat program.awk
/courtesy-page.html/ {  # if courtesy-page.html on current record
    sub(/^\#/,"",prev)  # remove leading # from previous record
    sub(/^\#/,"")       # and this
}
NR>1 {                  # on the first record prev buf is empty
    print prev          # output prev buffer only after first record
}
{
    prev=$0             # set prev buffer
}

Run it:

$ awk -f program.awk that_file.txt <(echo)  # the last part adds empty record that is ignored
                                            # its shorter than END block. Saving bytes!
a
b
c
d
  ## Mainteinance Page
  RewriteEngine On
  RewriteCond %{REQUEST_URI} !^/courtesy-page.html$
  RewriteRule .* https://%{HTTP_HOST}/courtesy-page.html [R]
e
f
g
h
网友答案:

This might work for you (GNU sed):

sed 'N;/!^\/courtesy-page.html/!{P;D};N;s/^#//Mg' file

Make a two line window and on encountering the required string, read a third line and remove # from the beginning of each of the three lines held in the pattern space. If the required string is not present, print then delete the first line of the window and append another.

相关阅读:
Top