Home > Archive > AWK > September 2006 > sed and grep with multiple files
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
sed and grep with multiple files
|
|
|
| Hi all, was hopeing you guys would be able trouble shoot this script.
It wil print to stdout all changes to files containing a command
argument and replaced it with the next argument. however, to change the
actual file, I can't get it right. it simply blanks one file and stops.
#! /bin/sh
# filename: replaceall
# Backup files are NOT saved in this script.
oldword=$1
newword=$2
echo "oldword = $oldword and newword = $newword"
grep -rl "$oldword" * | while read i
do
sed "s|$oldword|$newword|g" # $i > $i # this commented code causes a
problem
done
i'm because the following works for somebody else;
find . -type f -name '*.html' -print \
| while read i; do
mv $i ${i}.bak
sed "s*$1*$2*g" ${i}.bak > $i
done
| |
| Vassilis 2006-09-07, 3:56 am |
| Rupe wrote:
> Hi all, was hopeing you guys would be able trouble shoot this script.
> It wil print to stdout all changes to files containing a command
> argument and replaced it with the next argument. however, to change the
> actual file, I can't get it right. it simply blanks one file and stops.
>
> #! /bin/sh
> # filename: replaceall
> # Backup files are NOT saved in this script.
> oldword=$1
> newword=$2
> echo "oldword = $oldword and newword = $newword"
> grep -rl "$oldword" * | while read i
> do
> sed "s|$oldword|$newword|g" # $i > $i # this commented code causes a
> problem
> done
The problem lies in that you cannot open a file for reading (sed reads
input from $i) and at the same time redirect output to the same file.
> i'm because the following works for somebody else;
> find . -type f -name '*.html' -print \
> | while read i; do
> mv $i ${i}.bak
> sed "s*$1*$2*g" ${i}.bak > $i
> done
On the second example, a copy is made to the file. Then sed reads its
input from the copy and finally sed sends it ouput to the old file,
with its contents changed.
Hope this helps.
| |
|
| No but I finally got what I wanted;
find . -name '*.txt' -exec sed -i -r "s/qwe/plop/g" {} \;
this works a treat. doesn't even require a shell script file.
| |
| Chris F.A. Johnson 2006-09-12, 6:56 pm |
| On 2006-09-12, Rupe wrote:
> No but I finally got what I wanted;
>
> find . -name '*.txt' -exec sed -i -r "s/qwe/plop/g" {} \;
>
> this works a treat. doesn't even require a shell script file.
If you are going to use the non-standard -i option, use a suffix so
that a backup will be made of the file:
find . -name '*.txt' -exec sed -i.bak -r "s/qwe/plop/g" {} \;
--
Chris F.A. Johnson, author | <http://cfaj.freeshell.org>
Shell Scripting Recipes: | My code in this post, if any,
A Problem-Solution Approach | is released under the
2005, Apress | GNU General Public Licence
|
|
|
|
|