How to modify line that is located one line after a specific line using Perl?

Viewed 58

I have a file that contains the following lines:

...
# Check the date
date
...

I want to comment out the date command. But it occurses a few times in the file and I want to comment the date which is located right one line after the # Check the date, otherwise I would just use:

perl -i -pe 's:(.*date.*):#$1:' file

How can I improve my logic and comment out only the date right after the # Check the date comment?

2 Answers

Remember whether the previous line was the comment in a variable:

perl -pe 's/^(date)$/#$1/ if $prev; $prev = /^# Check the date$/;'

Honestly, I wouldn't use perl for this in-place edit, I'd turn to good old ed:

printf '%s\n' '/^# Check the date/+1s/^/# /' w | ed -s file

will add a # to the beginning of the line following the first line that matches the regular expression ^# Check the date and save the change.

printf '%s\n' '/^# Check the date/+1g/^date$/s/^/# /' w | ed -s file

will do the same only if the next line is date.

Related