PDA

View Full Version : linux / shell - question about find / replacing text


A Priest
01-28-07, 07:58 PM
I want to find some text lets called it 'This is my text' and I want to replace it with 'Some new text'. I can find the text using grep, but i dont know what to do from then. Any help?

Such a noob :(

Jase
01-28-07, 09:09 PM
You mean like the find/replace function in GUI word processors? I havent found any way of doing it via command line as yet - I use Pico or Vi (only use Vi when I absolutely have to lol) and they cant do it but thats not to say there isnt a program which will allow you to but I doubt it!

A Priest
01-28-07, 09:15 PM
i dont get it though, surely if you can use grep to find the string, replacing it should be relatively easy? it would have been quicker by now to do it the long way, but im a stubborn bastard that wont let it drop.

spann0
01-28-07, 09:43 PM
I would write a bit of perl to do it like:



#!/usr/bin/perl
#
$in = "This is my text";
$out = "Some new text";

while (<STDIN>) {
$_ =~ /$in/$out/gi;
print $_;
}



like cat File | ./blah.pl > outfile

A Priest
01-28-07, 09:50 PM
hmm, i dont know perl to be honest, just php.

Im not sure what this line does:

$_ =~ /$in/$out/gi;

can you explain it?

spann0
01-28-07, 09:53 PM
$_ =~ /$in/$out/gi;

$_ is the line of stdin and it replaces $in with $out
g is greedy so it will match more than once on the line I think
and i is case insensitive

its a swap in for out on the line

ApacheAnderson
01-28-07, 11:02 PM
http://unixhelp.ed.ac.uk/CGI/man-cgi?grep

A Priest
01-28-07, 11:34 PM
http://unixhelp.ed.ac.uk/CGI/man-cgi?grep

yeah i know, i got my results fine through grep, but i cant find a switch that replaces the found text with my new text.

mysatin
01-29-07, 12:10 AM
Use sed

Some examples at http://en.wikipedia.org/wiki/Sed or read the man page

helene
01-29-07, 02:58 AM
Use sed

Some examples at http://en.wikipedia.org/wiki/Sed or read the man page

For example, sed -e 's/Some text/Some New text/g' infile > outfile. Use a backslash (\) in front of any literal slashes in you search or replace text, and drop the final g if you only want to replace once per line. You can use more or less the same stuff in the search text as in grep. You can even have several -e 's/old/new/g' clauses if you want to do several replacements at once.

The man page is long, evil and complicated -- better look at the Wikipedia examples, or search for newbie stuff on the net if you get stuck.