The Austin Linux Meetup Message Board › Shell Script help

Shell Script help

A former member
Post #: 2
I have no experience with Shell Scripting so if anyone has a solution that does not involve shell that's welcome but here's my question otherwise.

(gist) I need to look through multiple files sitting in different sub directories under a parent dir find a string and replace it with a different string.

Here are the strings I am looking to find and replace:
NSLocalizedString(<key>, <comment>) to NSLocalizedStringFromTable(<key>, table, <comment>)

The key and comment have to remain same through the replace operation.
Examples:

1. NSLocalizedString(@"abc", @"xyz") --> NSLocalizedStringFromTable(@"abc"­, table, @"xyz") //
2. NSLocalizedString(someobject, somecomment) --> NSLocalizedStringFromTable(someobject, table, somecomment)

Again, I have no idea where to even beging all I have right now is :

#!/bin/sh

FILES=`ls $1 ./*.m`
for f in $FILES
do
echo "Processing file : $f"
done


which as you can see is just an example code
Bob C.
bob_carnaghi
Austin, TX
Post #: 65
Savaidya:

This can be done easily enough with Bash or scripting in general. I can't take the time to write it out right now, I'll post again later.

Bob
Bill S
user 9248335
Austin, TX
Post #: 125
#!/bin/bash
TOPDIR="$HOME/foo"
SEARCH_PATTERN='NSLocalizedString(\([^­,]*\),\([^)]*\))'
REPLACEMENT_PATTERN='NSLocalizedString­(\1, table, \2)'
find $TOPDIR -type f | while read f; do
echo ">>> Checking $f"
grep -q "$SEARCH_PATTERN" "$f"
if [ $? -eq 0 ]; then
TMPFILE=`mktemp /tmp/nslocalizedstrings-XXXXXXXXXX`
echo "Making substitutions in $f"
sed -e "s/$SEARCH_PATTERN/$REPLACEMENT_PAT­TERN/" < "$f" > $TMPFILE
cp $TMPFILE "$f".new
rm -f $TMPFILE
fi
done
Bob C.
bob_carnaghi
Austin, TX
Post #: 66
Savaidya:

Try this one-line snippet:

find -type f -name "*.<file-extension>" | xargs -I '{}' sed -i "s/<string1>/<string2>/­g" {}

Customize the following items per your needs:
1. Replace <file-extension> with the extension of the files you're looking for.
2. Replace <string1> with the string you want replaced in each file that is found.
3. Replace <string 2> with the string you want inserted in each file that is found.

You can run it from the command line, or wrap it in a script. There's no loop necessary, as it will search the current directory and all the directories below. It can be tailored further by adding additional command parameters as needed. An amended version of this pipe is working well for me on a daily basis in several scripts that I run from cron jobs.

Bob Carnaghi
Powered by mvnForum

Our Sponsors

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy