| Author |
find a string pattern in files and replace it
|
|
|
| Hi,
I searched a file system and found a string pattern in several files. I
want to change that string to other string. Can anyone shed some light
on how to do it.
Thanks in advance.
Mike
| |
| Michael Tosch 2006-09-19, 1:32 pm |
| Mike wrote:
> Hi,
> I searched a file system and found a string pattern in several files. I
> want to change that string to other string. Can anyone shed some light
> on how to do it.
> Thanks in advance.
> Mike
>
#!/bin/sh
pattern="foo"
replacement="bar"
find . -exec grep -l "$pattern" {} \; |
while read file
do
echo "replacing $pattern by $replacement in file $file"
cp -p "$file" "$file.orig"
sed "s/$pattern/$replacement/g" < "$file.orig" > "$file"
# only if you are sure # rm "$file.orig"
done
--
Michael Tosch @ hp : com
| |
| rakxzo@gmail.com 2006-09-19, 1:32 pm |
|
Mike wrote:
> Hi,
> I searched a file system and found a string pattern in several files. I
> want to change that string to other string. Can anyone shed some light
> on how to do it.
> Thanks in advance.
> Mike
You can probably do this with bash and awk. Use a small for loop that
iterates through the files that you need and then call an awk command
to replace the string you need on each of the files as it goes through.
This is a decent explanation of awk and replacing stuff.
http://www.student.northpark.edu/pe...wk/gawk_str.htm
| |
| Michael Paoli 2006-09-20, 1:29 pm |
| Michael Tosch wrote:
> Mike wrote:
>
> #!/bin/sh
> pattern="foo"
> replacement="bar"
> find . -exec grep -l "$pattern" {} \; |
> while read file
> do
> echo "replacing $pattern by $replacement in file $file"
> cp -p "$file" "$file.orig"
> sed "s/$pattern/$replacement/g" < "$file.orig" > "$file"
> # only if you are sure # rm "$file.orig"
> done
Ah, and then the "excitement" when someone does something like:
$ mkdir 'bar
> ' 'bar
> /etc'
$ echo foo >'bar
> /etc/passwd'
http://www.rawbw.com/~mp/unix/sh/#G...mming_Practices
| |
| Stephane Chazelas 2006-09-21, 1:25 pm |
| On 19 Sep 2006 11:07:03 -0700, Mike wrote:
> Hi,
> I searched a file system and found a string pattern in several files. I
> want to change that string to other string. Can anyone shed some light
> on how to do it.
[...]
I generally do (using GNU grep, GNU xargs and perl):
grep -rlZ pattern /some/dir | xargs -r0 PERL -pi -e '
s/pattern/replacement/g'
--
Stephane
|
|
|
|