April 13 2022, 12:54#

regular expression - How can I use sed to replace a multi-line string? - Unix & Linux Stack Exchange

Lien : https://unix.stackexchange.com/questions/26284/how-can-i-use-sed-to-replace-a-multi-line-string/26290#26290

Pour faire suite à mon précédent post, j'ai besoin d'activer la compression de logrotate en décommentant la ligne #compress juste après le commentaire explicatif # uncomment this if you want your log files compressed.

Pour ce faire :

sed '/# uncomment this if you want your log files compressed/{n;/#compress/{s/#compress/compress/;p;d;}}' /etc/logrotate.conf

Quelques explications :

  1. On recherche le pattern # uncomment this if you want your log files compressed
  2. Si on trouve, on passe à la ligne suivante n;
  3. On recherche le pattern #compress
  4. Si on trouve, on substitut #compress par compress
  5. On imprime p;
  6. On supprime l'occurence d;

Cheatsheet :

:  # label
=  # line_number
a  # append_text_to_stdout_after_flush
b  # branch_unconditional
c  # range_change
d  # pattern_delete_top/cycle
D  # pattern_ltrunc(line+nl)_top/cycle
g  # pattern=hold
G  # pattern+=nl+hold
h  # hold=pattern
H  # hold+=nl+pattern
i  # insert_text_to_stdout_now
l  # pattern_list
n  # pattern_flush=nextline_continue
N  # pattern+=nl+nextline
p  # pattern_print
P  # pattern_first_line_print
q  # flush_quit
r  # append_file_to_stdout_after_flush
s  # substitute
t  # branch_on_substitute
w  # append_pattern_to_file_now
x  # swap_pattern_and_hold
y  # transform_chars

Tags : linux unix sed logrotate log cheatsheet