canoodle
canoodle

Reputation: 516

vim - why will search find it but search and replace not? (this escaped special char pattern)

want to search and replace in vim, the /find finds the pattern but :s%//g will not?

have a script that monitors software raid (if interested check it out https://dwaves.org/2019/09/06/linux-server-monitor-software-raid-mail-notification-on-failure/)

echo "=== smart status of all drives ==="| tee -a /scripts/monitor/raid_status_mail.log

# want to search and replace the /path/to/file.sh with $LOGFILE

# searching for the pattern works like charm
/\/scripts\/monitor\/raid_status_mail.log

# but replacing it won't
:s%/\/scripts\/monitor\/raid_status_mail\.log/\$LOGFILE/g

# what does one do wrong?

should replace /scripts/monitor/raid_status_mail.log with $LOGFILE

Upvotes: 0

Views: 68

Answers (2)

barthelemypousset
barthelemypousset

Reputation: 21

You inverted the beginning s%. Use %s instead.

Also, you use / as separation for the different fields, it works but makes the command less readable. You can replace the separation character by anything else. You could use : for example:

%s:/scripts/monitor/raid_status_mail.log:$LOGFILE:g

One last tip: install vim-over

This will highlight your searches in live while replacing something in vim.

Upvotes: 2

Inian
Inian

Reputation: 85550

The substitution operation needs to be prefixed with %s and not the other way around as s%. So doing

%s/\/scripts\/monitor\/raid_status_mail\.log/\$LOGFILE/g

should work as expected. Or just the Vim's equivalent ex in command line mode as

printf '%s\n' "%s/\/scripts\/monitor\/raid_status_mail\.log/\$LOGFILE/g" w q | ex -s file

Upvotes: 3

Related Questions