[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Replacing text in multiple files
From: |
Jaya Reddy |
Subject: |
Replacing text in multiple files |
Date: |
Mon, 12 Nov 2001 20:52:44 +0000 |
Hi,
Thank you very much for maintaining the GNU Awk User's Guide. The guide is
very good - simple, clear, elaborative and very well compiled. I learnt awk
in a day!!!
I had a problem "replacing a string in multiple files".
I am using GNU Awk 3.0.4 on Redhat Linux 6.2.
gawk '{gsub("oldstr","newstr"); print $0}' file1 > file1
This command doesnot replace the oldstr in file1. I thought it would do it,
after reading the following paragraph from your guide.
A redirection appears after the print or printf statement. Redirections in
awk are written just like redirections in shell commands, except that they
are written inside the awk program.
May be I misinterpreted that. Anyway, it worked with awk redirection.
gawk '{gsub("oldstr","newstr"); print $0 > file1}' file1
(or)
gawk '{gsub("oldstr","newstr"); print $0 > FILENAME}' file1
Can u please tell me, why is this discrepancy (my understanding)?
I have this as a tip, I thought would be helpful to other people.
If you feel, it is worth including in the guide, I wish you would do so.
I had a hardtime finding an answer to 'how to replace text in mulitiple
files'. It took me a lot of time to figure out to write in to the file which
is given as the input to awk script. I was using the shell redirection which
wasn't work and after enough of time and trouble i came to know that I have
to use awk redirection. Even 'sed' could not be of any help and I still dont
know how to do it using sed. It would be great if u can help me with that.
The following command replaces all the instances of 'oldstr' to 'newstr' in
all the files under the directory "/home/gnuuser/mydir" recursively.
find /home/gnuuser/mydir -type f -exec gawk '{gsub("oldstr","newstr"); print
$0 > FILENAME }' {} \;
Note: The redirection should be applied to the print command of awk, and not
to the shell. Otherwise, the replacement will not take place in the input
file.
Use the following command if you want the replacement to be done ONLY in
"/home/gnuuser/mydir" but not under its subdirectories. The only difference
in this command is the "maxdepth" argument to find.
find /home/gnuuser/mydir -type f -maxdepth 1 -exec gawk
'{gsub("oldstr","newstr"); print $0 > FILENAME }' {} \;
Happy awk'ing.
Go free source.
Thanks
Jay
_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp
- Replacing text in multiple files,
Jaya Reddy <=