简体   繁体   中英

Interactive Find and Replace - Bash script

I understand this question has been asked a lot in the bash / perl world.

I can appreciate the answer here Interactive search and replace from shell

:argdo %s#SEARCH#REPLACE#gec |update

This works okay for me, and I do like and use vi.

But I want to take this concept to the next level

the answer given at the above link is as follows: sed -i -e 's/foo/bar/g' filename again this works.

so in the interest of making this an executable / interactive script.. I tried something like this:

#!/bin/sh

read -r -p "Search For: " FIND 
read -r -p "Replace With: " REPLACE 
read -r -p "Full Path To File: " FILE 

sed -i -e 's/"${FIND}"/"${REPLACE}"/g' "$FILE" 

however, if you are reading this, you probably know that you can't run sed like this inside a bash script.

Any thoughts on making this find_replace.sh a working script?

Thanks for reading.

First of all, you should switch the single quotes and double quotes on your last line. In that way bash will replace your variables with the values. Second of all, you should add some escaping around the FIND and REPLACE values. For the case where in one would use values containing / characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM