find or replace without using sed
Hi all,
I am working on writing a script for find and replace a string using sed. But know I want to write without using sed. Is it possible and someone Please help me write this code. Thanks & Regards Adarsh Sharma |
# substitute (find and replace) "foo" with "bar" on each line
awk '{sub(/foo/,"bar");print}' # replaces only 1st instance gawk '{$0=gensub(/foo/,"bar",4);print}' # replaces only 4th instance awk '{gsub(/foo/,"bar");print}' # replaces ALL instances in a line more examples on http://www.catonmat.net/blog/wp-cont...9/awk1line.txt |
You could also write a bash script to loop through the file and then change the necessary item(s)
|
Thanks but I am using a user input variable and file name to replace.
Here is my command sed command : In sed we have to quote in " rather than ` to accept variables sed "s/$findstring/$replacestring/g" $filename > /root/Desktop/output1.txt Your command is awk '{gsub(/foo/,"bar");print}' # replaces ALL instances in a line But we have to mention filename, findstring variable and replace string variable. Thanks |
Hi grail , I also want the same thing.
First Loop through file with each word. If condition to match and code to replace. Thanks & Regards Adarsh |
Quote:
Code:
awk -vfind=$findstring -vreplace=$replacestring 'gsub(find,replace)' $filename > /root/Desktop/output1.txt |
Yes It works.
Thanks for your kindness. But i didn't work as i expected.I expect to have changes in original file filename.txt but I checked, it displays only replacements i.e findstring replacestring in new file and also I checked with below command : awk -vfind=$findstring -vreplace=$replacestring 'gsub(find,replace)' $filename It displays [root@ws-test Desktop]# bash adarsh2.sh find2.txt adarsh sharma sharma sharma sharma sharma sharma Script executed successfully I want changes in original file. Best Regards Adarsh Sharma |
You can use a temp file.
awk -vfind=$findstring -vreplace=$replacestring 'gsub(find,replace)' $filename >$filename.tmp mv $filename.tmp $filename And it is my first post. :D |
Thanks this has helped me alot.
|
Quote:
at the end of your sed command where you were not replacing the original file. As has been indicated, awk does not have the '-i' option of sed to perform the change in place so you require a temp file and move. |
All times are GMT -5. The time now is 08:33 AM. |