Friday, August 02, 2013

Do You Program?

What exactly is it that you do?

Well today I hit a great example of what it is that I do,  not just what someone in my position does but what I do.

Here is the problem to solve.  There is a file call example_config which contains the following information

#File containing thing_to_change
blahblah1=XXXXX
blahblah2=YYYYY
target1=thing_to_change
blahbblah3=not_thing_to_change   
value1=thing_to_change
blahblah4=thing_to_change_NOT

I want to change the string thing_to_change to thing_changed.   HOWEVER only for the lines target1 and value1 not anywhere else.

The tool of choice is SED  a Unix utility for editing files.  SED is short for Stream EDitor.

The quick and dirty way to do this would be the statement

sed -i "s/thing_to_change/thing_changed/g" example_config  

This says scan the file example_config (the last parameter does that) and substitute (the 's' does this) all occurrences (the 'g' gets you all)  of thing_to_change to thing_changed (/thing_to_change/thing_changed/ does this) save the change in the file example_config (the -i does this part).  I can read this sort stuff forwards and backwards in my sleep.

But this would give you the following:

#File containing thing_changed
blahblah1=XXXXX
blahblah2=YYYYY
target1=thing_changed
blahbblah3=not_thing_changed   
value1=thing_changed
blahblah4=thing_changed_NOT

See, not even close.  But you're smart and figured that out all ready.

What to do what to do... Well you could to this:

sed -i "/target1=thing_to_change/target1=thing_changed/" example_config
sed -i "/value1=thing_to_change/value1=thing_changed/" example_config

This is the me part.  I just hate stuff like this.  This just seems clunky and clumsy.

I dug around in one of my favorite books "sed & awk" to find the answer.  I have had this book since 1992.  Seems like longer.  This book is like an old friend.

I figured out the following.

sed -i "s/\(value1|target1\)=thing_to_change/\1=thing_changed/g" example_config

This says, scan the file example_config and replace value1 or target 1 =thing_to_change with which every string you matched =thing_changed  in the file example_config.

One scan of the file and you get this:

#File containing thing_to_change
blahblah1=XXXXX
blahblah2=YYYYY
target1=thing_changed
blahbblah3=not_thing_to_change   
value1=thing_changed
blahblah4=thing_to_change_NOT

Now is reality thing_to_change, thing_changed, value1, and target1 are variables and would change everytime this script it run but explaining that would take even longer.  This is just simple example of what I do.


1 comment:

  1. An example of what I do ... "Ms. Lee, why won't this computer work?" "See that little wheel spinning? That means it is thinking. A computer can't do anything until it is done thinking."

    ReplyDelete