Click to See Complete Forum and Search --> : using bash to alter files


chris27
12-04-2002, 09:32 PM
Hi all. I have a simple BASH questions that I need help with.

How can you use bash to alter one line, (say in the middle) of a file?
For example, lets say I have a list of 5 variables in a file:
variable1="Hi"
variable2="Hello"
variable3="Greetings"
variable4="Hi, there."
variable5="Yo!"

and let's say that I use another file to call up these variables from time to time. However, sometimes I might want to permanently change the value of a variable without having to pull up the variable file in Emacs. How can I get a program to permanently change variable2="Hello" to variable2="Hello all!"?

Thanks...
:confused:

Rüpel
12-05-2002, 03:00 AM
sed 's/^variable2=".*"/variable2="Hello all!"/' hello > hello.tmp; mv hello.tmp hello

Rüpel
12-05-2002, 03:28 AM
ahh. a little scripting in the morning is always nice (it's 8am here currently) :cool:

you may even move that line into a script, just for the fun of it (and you don't have to grep your history the next time you want to change a variable) ;)

~/dev [306] > cat hello
variable1="Hi"
variable2="Hello"
variable3="Greetings"
variable4="Hi, there."
variable5="Yo!"
~/dev [307] > ./chgreet 2 hello 'Hello all!'
~/dev [308] > cat hello
variable1="Hi"
variable2="Hello all!"
variable3="Greetings"
variable4="Hi, there."
variable5="Yo!"
~/dev [309] > cat chgreet
#!/bin/bash
if test "$#" -ne 3
then
echo "usage: chgreet n f g"
echo " where n is the number of the variable to change [n=2 -> variable2]"
echo " f is the file containing the variables"
echo " g is the new greeting - remember to put it in quotes if it contains spaces!"
else
sed "s/^variable$1=.*/variable$1=\"$3\"/" $2 > $2.tmp
mv $2.tmp $2
fi
~/dev [310] >

chris27
12-05-2002, 09:38 PM
R-el,

That was nice! Thanks. Im going to make that script a permanent member of my collection!


A quick question if I may....
if test "$#" -ne 3
How does one write this line using the if [....]; then format?


Also can you clarify for me what symbol is suppsed to be in place of the '?' on the line below? My computer did not catch the symbol you used.
......variable$1=.*/variable$1=?" $3?"/" .........


While Im at it.. is it possible to get BASH to colorize output? If yes, what is the command for it?


Thanks again!

baldguy
12-05-2002, 09:49 PM
in (ba)sh scripting the "[" operator is equal to test (after an if statement), I believe that works in ksh and csh too ,but I'm not sure

l01yuk
12-06-2002, 10:05 AM
I believe that works in ksh and csh too works in ksh, don't know about csh, it can be used for any of the flow controls: while; for; until...

You have to remember to leave a space between the [ and the expression and the closing ]. Not doing this is a common cause of newbie bugs, caused me a few, um, frustrations, anyway.