LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Linux command to find and replace string within text file (https://www.linuxquestions.org/questions/linux-newbie-8/linux-command-to-find-and-replace-string-within-text-file-685722/)

chips11 11-24-2008 07:21 AM

Linux command to find and replace string within text file
 
I want to run a .sh script that will find all instances of gggggg in a single text file, and replace it with hhhhhhh.

I have been looking online and am not sure if I need to use grep or sed command and when I use the said command how to format it in my shell script.

I was trying to use
sed 's/ggggggg/hhhhhhh/g' public/usr/folder/myfile.txt

But I think you cant use the path using sed, so within my sh script, can how do I get it to run se within the directory I want, so that I can then simply put the file name, I thought maybe a cd command.

Maybe I should be using grep though.

pixellany 11-24-2008 07:32 AM

Quote:

But I think you cant use the path using sed
Why do you say that? You can put anything you want in the SED syntax. Do mean path in the "s" command, or the path in the filename? (In this context, I suspect the latter)

Note that--regardless of where used--pathnames need to be in one of two forms:
1. Relative to the current position
2. Absolute, starting with "/"


Quote:

Maybe I should be using grep though.
GREP doesn't do find and replace....

I would go to http://tldp.org and get the Bash Guide for Beginners. Also, some excellent tutorials here: http://www.grymoire.com/Unix/

colucix 11-24-2008 07:36 AM

Quote:

Originally Posted by chips11 (Post 3352669)
But I think you cant use the path using sed

Why not? sed accepts file names with or without a relative or absolute path, as all the linux commands which accept a file name as argument. Otherwise you can always use the cd command, but it depends only on what is more comfortable for you.

Moreover, if you want to edit the file in place, use the -i option of sed (test it on a dummy copy of the same file before actually do).

Edit: too late....

chips11 11-24-2008 08:13 AM

It was because it was saying something about the path in the error message I was receiving that I said about the path, message from the server, but I probably misunderstood it..

I added the -i and it is now working fine

sed -i 's/gggg/hhhhhhhhhhhhh/g' /path/to/file.txt

Thanks ever so much, really appreciate it.

pixellany 11-24-2008 11:55 AM

We like happy endings---thanks for the follow-up

estabroo 11-24-2008 02:25 PM

rpl is a great command for doing this, it even supports doing it recursively


All times are GMT -5. The time now is 08:46 AM.