Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 2 down vote accepted

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

share|improve this answer
In this instance, NEW_STRING should be $1 to accomplish your goal. – jnovack Mar 27 '13 at 15:11
$1 is the passed name of the file that has to be filtered. – Riccardo Marotti Mar 27 '13 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 '13 at 16:58
Yes, you are right. I didn't read the question carefully enough :) I'll update the answer. – Riccardo Marotti Mar 27 '13 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 '13 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))' "$@"
share|improve this answer
Thank you Lauri! – Ben Apr 1 '13 at 19:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.