How to do a find & replace on text files?

Get help. Get answers. Let others lend you a hand.

Moderator: Mr_Noodle

How to do a find & replace on text files? Sat Jan 12, 2019 7:11 am • by apedonks
I've searched the forums and Google extensively. I want to find & replace a certain text string inside a markdown file, every time it is saved. So I'm using "date last modified" (less than 1 min) as a trigger, and I think I have to use a script to do the find & replace bit. I've tried the script
Code: Select all
sed -i -e 's/old_string/new_string/g' $1


But that returns
Code: Select all
Error] Shell script failed: Error processing shell script


I tried to add an exit code of 0, and that removes the error, but it has no result. I tried a variation where it creates a new file:

Code: Select all
sed -n 's/old_string/new_string/gpw newfile.md' $1

exit 0


That does create a new file, but it's empty. I tried the same thing an hour ago, and that did work, but it only copied the line with the replaced string, not the rest of the file. I can't reproduce that now.

Can anyone help me out?
apedonks
 
Posts: 2
Joined: Sat Jan 12, 2019 6:29 am

Re: How to do a find & replace on text files? Mon Jan 14, 2019 11:29 am • by Mr_Noodle
Not sure if this is the issue but try putting double-quotes around the $1 argument. If the path has any spaces in it, it will end up being interpreted as two arguments.

Otherwise, does the script work outside of Hazel?
Mr_Noodle
Site Admin
 
Posts: 7756
Joined: Sun Sep 03, 2006 1:30 am
Location: New York City

I did find out that on a Mac, you need an extra argument that provides the file extension of an automatically created backup file. So in Terminal, the following script works fine:
Code: Select all
sed -i '.bak' 's/old_string/new_string/g' filename.md


This simple Terminal command changes the old_string to the new_string inside the updated filename.md file, and additionally creates a filename.md.bak backup file with the contents of the old file.

Doing the same as a script in Hazel gives the error. When I replace the $1 or "$1" with a hard-coded reference to the file path I want to test, same error.
apedonks
 
Posts: 2
Joined: Sat Jan 12, 2019 6:29 am

Does the path have any spaces or other non-alphanumeric characters?
Mr_Noodle
Site Admin
 
Posts: 7756
Joined: Sun Sep 03, 2006 1:30 am
Location: New York City


Return to Support