automating find and replace on bash scrips?y

Chris F.A. Johnson cfaj-uVmiyxGBW52XDw4h08c5KA at public.gmane.org
Sun Nov 4 20:04:55 UTC 2007


On Sun, 4 Nov 2007, Alex Maynard wrote:
>
> I am getting a bit stuck on an (admittedly very simple) bash script to 
> automate find/replace in bash.
>
> What I'm aiming for is:
>
> File $1: text file on which I want to run multiple find/replaces
>
> File $2: text file with list of what to replace by what
>
> To make it concrete, say I wanted to replace capital by lower case letters. 
> Then I might have File $2 look like:
> A a
> B b
> C c
> etc.
>
> The part I know how to do is:
>
> sed 's/B/b/' <$1>tmp_sed
> cp tmp_sed $1
>
> Adding a loop around this shouldn't be a problem either.
>
> The part I'm stuck on is: On say, the second iteration of the loop,
> how do I get bash or sed to obtain "B" and "b" automatically from
> the second line of file $2.
>
> If anyone has any tips or pointers, I'd be grateful.

    The easiest way is to turn the file with the search/replace strings
    into a sed script:

s/A/a/  ## add the g command?  s/A/a/g
s/B/b/
s/C/c/

    You can automate the conversion of the file to a script:

awk '{ printf "s/%s/%s/\n", $1, $2 }'

    More will have to be done if any of your strings contain a slash.


    Then you can run:

sed -f "$2" "$1" > tmp_sed && cp tmp_sed "$1"


-- 
    Chris F.A. Johnson, webmaster         <http://woodbine-gerrard.com>
    ========= Do not reply to the From: address; use Reply-To: ========
    Author:
    Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
--
The Toronto Linux Users Group.      Meetings: http://gtalug.org/
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists





More information about the Legacy mailing list