replace string foo to bar AND bar to foo in the same file

replace string foo to bar AND bar to foo in the same file

Shlomi Fish shlomif at gmail.com
Wed Sep 25 15:38:26 IDT 2013


Hi vordoo,


On Wed, Sep 25, 2013 at 2:24 PM, vordoo <vordoo at yahoo.com> wrote:

>  Hi,
>
> I know how to: sed -i 's/foo/bar/g' *.txt
>
> But how do I: replace string foo to bar AND bar to foo in the same file??
>
>
This is not hard to do using perl:

shlomif at telaviv1:~$ perl -ple 'my $s1 = "foo"; my $s2 = "bar";
s/((?:\Q$s1\E)|(?:\Q$s2\E))/(($1 eq $s1) ? $s2 : $s1)/ge'
Hello
Hello
The foo bar
The bar foo
bar Hello
foo Hello
foo zoomla
bar zoomla
foo bar ||| bar foo
bar foo ||| foo bar

Add the -i flag to edit a list of files in place (it in fact originated
from an old version of perl and was incorporated into GNU sed - it's not a
standard flag.) Can be done using ruby too, but I'm less fluent in it.

Regards,

-- Shlomi Fish

-- 
------------------------------------------
Shlomi Fish http://www.shlomifish.org/

Electrical Engineering studies. In the Technion. Been there. Done that.
Forgot a lot. Remember too much.

Please reply to list if it's a mailing list post - http://shlom.in/reply .
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.cs.huji.ac.il/pipermail/linux-il/attachments/20130925/09d2bbe6/attachment-0001.html>


More information about the Linux-il mailing list