3
I often want to automate this sort of task in a shell script:
if the line:
SOMEKEY=SOMEVALUE
exists in a file, then change it to
SOMEKEY=SOMEOTHERVALUE
otherwise, append the line SOMEKEY=SOMEOTHERVALUE
in the file.
How could I go about this? I think I could do it using a combination of grep
and sed
, but I'm sure it's a common enough task that someone has already worked out an elegant solution.
By the way, when replacing I would normally do something like this
sed -i 's/old/new/g' fname
But it means I have to be very careful when composing my regular expressions, so as not to make a mistake. Is there an easy way to "preview" what changes which would occur from my call to sed
without actually stomping on the file?
Missed that last question: If you just want to preview your changes, omit the option
-i
and code: yoursedcommand|grep fname -
That will compare the outcome of your command with the original filefname
– ktf – 2011-10-17T12:08:10.683i tried, for example,
sed 's/HISTSIZE/SPAM/g' ~/.bashrc | grep ~/.bashrc
but didn't see any output. – wim – 2011-10-17T12:24:33.713So sorry - stupid typo (obviously I was thinking about something else...) Correct is: yoursedcmd
| diff fname -
– ktf – 2011-10-17T12:37:04.597yes i thought you might have meant
diff
, but when i tried that i getdiff: missing operand after
/home/wim/.bashrc'` – wim – 2011-10-17T12:40:31.023Don't forget the second argument to diff: it's only a single minus sign (
-
) which indicates that the 2nd file for comparison shall be read from stdin – ktf – 2011-10-17T13:07:36.483oops, you were right i missed the
-
. thanks ! – wim – 2011-10-17T22:30:37.913