In a Regex, \s Also Matches Newlines, So One Pattern Can Span Two Lines

In progress Ansible Linux

\s means any whitespace: space, tab, and newline. A pattern that is only ever tested line by line (as sed applies it) behaves; the same pattern run against a whole file in multiline mode can start on one line and finish on the next.

The Case

Ansible's ansible.builtin.replace runs Python's re over the whole file with MULTILINE, so ^ and $ match at every line, but \s still crosses line breaks. The task meant to comment out swap entries:

regexp: '^(\s*[^#\n]+\s+\S+\s+swap\s+.*)$'
replace: '# \1'

On a Debian fstab, the root entry is followed by the installer's comment:

UUID=69d2... /               ext4    errors=remount-ro 0       1
# swap was on /dev/sda5 during installation

[^#\n]+ consumed the root line, \s+ matched the newline, \S+ matched #, then swap matched the comment. The match started on the root line, so # landed in front of it: the root filesystem was commented out, and the node booted read-only from then on (see With No Active Root Entry in fstab, systemd Leaves the Root Filesystem Read-Only on Every Boot).

Writing It Safely

References

Review cards

Flashcard Why can a regex that's correct line by line edit the wrong line when Ansible's replace runs it?

replace matches over the whole file in multiline mode, and \s also matches newlines, so the pattern can start on one line and finish on the next.

Flashcard What should you use instead of `\s` to match whitespace inside a single line?

[ \t] (or [^\S\n]): spaces and tabs, but never a newline.

Flashcard Besides fixing the regex, what keeps a text-editing task from silently breaking a file again?

An assert on the end state after the edit (here: / still has an active fstab entry), tested against a real sample file with its comments.