bug-gnu-utils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Replacing text in multiple files


From: Jim Meyering
Subject: Re: Replacing text in multiple files
Date: Mon, 12 Nov 2001 22:46:29 +0100
User-agent: Gnus/5.090004 (Oort Gnus v0.04) Emacs/21.1.50 (i686-pc-linux-gnu)

address@hidden (Paul Jarc) wrote:
> "Jaya Reddy" <address@hidden> wrote:
>> gawk '{gsub("oldstr","newstr"); print $0}' file1 > file1
>
> In this command, the shell opens and truncates file1 for output before
> gawk ever sees it.  Use this instead:
>   gawk '{gsub("oldstr","newstr"); print $0}' file1 > file2
>   mv file2 file1
> This has the added advantage that file1 is updated atomically by mv;
> anything that looks at file1 at any time will see either the complete
> old version or the complete new version - never a half-written new
> version.
>
>> find /home/gnuuser/mydir -type f -exec gawk '{gsub("oldstr","newstr");
>> print $0 > FILENAME }' {} \;
>
> This should work too:
> find /home/gnuuser/mydir -type f -exec \
> sh -c 'gawk "$0" "$1" > "$1.tmp"; mv "$1.tmp" "$1"' \
> '{gsub("oldstr","newstr"); print $0}' '{}' \;
>
> Here, the redirection is done by the shell invoked by find.

You can also use Perl.
This presumes you have GNU find and xargs:

  find . -type f -print0 |xargs -0 perl -pi.bak -e 's/oldstr/newstr/g'

You might want to limit the process to files that will
actually be changed -- sometimes it's best not to update timestamps,
and if you're making backups as this is, there's no point in making
a .bak file if it's identical to the original:

  find . -type f -print0 | grep -l oldstr \
    | xargs -0 perl -pi.bak -e 's/oldstr/newstr/g'



reply via email to

[Prev in Thread] Current Thread [Next in Thread]