简体   繁体   中英

find and replace shell using file as input for search and for replace

I need to replace several chunks of text inside some php scripts...

i have:

find . -name 'products.php' -exec grep --silent 'TEXT_TO_FIND' {} \; -exec ls {} \; -exec sed -i 's/TEXT_TO_FIND/REPLACE_TEXT/g' {} \;

this work, but i have text of about 2 ou 3 lines..

so i remember to create a find.txt with my find text and another replace.txt with the replacement text..

my question is.. how can i use this files as inputs in the above command..

something like:

find . -name 'products.php' -exec grep --silent `cat find.txt` ...

Best regards Bruno

You probably have to go to something more data oriented than pure-bash/coreutils. If you have access to Python on your site:

#!/bin/python
with open("find.txt","r") as f:
    fs = f.read().trim("r")

with open("replace.txt","r") as f:
    rs = f.read().trim()


# you probably have to loop other the following lines
# Once for every file:
with open("src.txt","r") as f:
    src = f.read()

modified = src.replace(fs,rs)
if modified := src:
    with open("src.txt","w") as f:
        f.write(modified)

This is only a starting point . You will probably have to improve it. Feel free to ask an other question if you're stuck on something!


Here is a transcript of my tests:

sh$ cat src.txt 
AAA
BBB
CCC
DDD
CCC
DDD
EEE
FFF
sh$ cat find.txt 
CCC
DDD
EEE
sh$ cat replace.txt 
XXX
YYY
ZZZ
sh$ python m.py
sh$ cat src.txt 
AAA
BBB
CCC
DDD
XXX
YYY
ZZZ
FFF

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