Automator: How to replace a particular string with the filename?
Within Automator, how can I replace a particular string in many different files with the filename of each file?
// UPDATE
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?
Solution 1:
You can use a Run Shell Script
action, with a script like this:
basename=${1##*/}
tmp=`mktemp -t $$`
sed -e "s/STRING_TO_BE_REPLACED/$basename/g" "$1" > $tmp && mv $tmp "$1"
with Pass input:
set to as arguments
:
Solution 2:
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"
done
Another option using Ruby:
ruby -i -pe '$_.gsub!("stringToBeReplaced", File.basename($FILENAME))' "$@"