2

I am trying to write a shell script to replace the SEARCH string by REPLACE string in all the files of the current directory (directory where my script remains).

The condition I have is : the script should replace the 'search string' to 'replace string' in all the files except my shell script.

I tried sed command in console. It worked as I have expected. But when I added this sed command to my script, it throws an error.

The command in my script(replace.sh) is :

search_str=is;
replace_str=IS;
sed -i.bak s/$search_str/$replace_str/g !(replace.sh)

The error I get is:

./replace.sh: line 11: syntax error near unexpected token '('
./replace.sh: line 11: 'sed -i.bak s/$search_str/$replace_str/g !(replace.sh)'

Hope you can help me.. Thank you in advance..

2
  • find . -name "." |xargs sed -i "s/searched_Text/replacement_Text/g"
    – Setekh
    Commented Jan 14, 2016 at 7:03
  • Enable the shop extglob with shopt -s extglob in your script.
    – Hastur
    Commented Jan 14, 2016 at 12:27

3 Answers 3

0

You just need to enable extglob in the script, at least in that point.

#!/bin/bash
search_str=is                  # Variable Initialization 
replace_str=IS
                               # Other stuffs other 7 lines in your script
Old_State=$(shopt -p extglob)  # Here you save the value of shopt extglob

shopt -s extglob               # Here you change (if needed) that value
sed -i.bak s/$search_str/$replace_str/g !(replace.sh)

$Old_State                     # Here you restore the previous value of extglob
                               # Other code ...    

I propose you to save and restore the status of the extglob just in case the script is long and it has some other command that need that status of the option... Of course if you are writing your own script you can decide to write it with extglob enabled and to be consistent with it: so you need only to add shopt -s extglob in the script before that line (#11).

More info with help shopt from the shell.

1

This is because extended patterns like !(replace.sh) is not enabled. Add shopt -s extglob to your script.

0

after working a bit in your problem i think i may have the solution

#!/bin/bash

search_str=is;
replace_str=IS;
find .  -maxdepth 1 -type f ! -wholename $0 -exec sed -i s@$search_str@$replace_str@g {} \;

I have used find with -maxdepth 1 top get the sed change applied to all the files in the folder where the script is. ! -wholename $0 makes the script avoid be used on itself

Regards

1
  • 1
    Note: "! -wholename $0 makes the script avoid be used on itself" it works when you do chmod u+x to your script and you execute it with ./replace.sh but it will fail if you run your script with /bin/bash replace.sh. PS>You forget to write the extension in the -i.bak option, it can be useful ;)
    – Hastur
    Commented Jan 14, 2016 at 12:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .