Within Automator, how can I replace a particular string in many different files with the filename of each file?


Using a "Run Shell Script" process I am able to get the body of a test file (an html file), with the string correctly replaced, but the modified file isn't being saved. I just see the file's contents as text in the "results" pane of "Run Shell Script". How do I:

a) Get the file name instead of the entire filepath? b) Save the modified file? Do I need another step when using sed?

enter image description here

2 Answers 2


You can use a Run Shell Script action, with a script like this:

tmp=`mktemp -t $$`
sed -e "s/STRING_TO_BE_REPLACED/$basename/g" "$1" > $tmp && mv $tmp "$1"

with Pass input: set to as arguments:

enter image description here

  • In this instance, NEW_STRING should be $1 to accomplish your goal.
    – jnovack
    Mar 27, 2013 at 15:11
  • $1 is the passed name of the file that has to be filtered. Mar 27, 2013 at 15:47
  • Yes, but the goal was to replace the string with the filename. You were correct in showing the syntax, but to accomplish the goal, you would have to replace NEW_STRING with $1. I was augmenting, not critiquing.
    – jnovack
    Mar 27, 2013 at 16:58
  • Yes, you are right. I didn't read the question carefully enough :) I'll update the answer. Mar 27, 2013 at 17:04
  • Thanks, very educational! That regex gives me a headache but I'm going with it :) I want to set this up as a mini-app, that I can drag and drop text files onto, with them resaved with the change. The resaving isn't happening though. Am I missing an obvious step?
    – Ben
    Mar 28, 2013 at 16:58

This would work with multiple files and filenames with special characters:

for f in "$@"; do
    [[ ! -f $f ]] && continue
    text=$(cat "$f")
    printf %s "${text//stringToBeReplaced/${f##*/}}" > "$f"

Another option using Ruby:

ruby -i -pe '$_.gsub!("stringToBeReplaced", File.basename($FILENAME))' "$@"

You must log in to answer this question.

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