Maheen Nasir Maheen Nasir - 1 year ago 119
Bash Question

How to do a change in string of file using shell script

I have a config file xyz.conf which contains some fields and I want to do little change in between it according to the requirement of user. (i.e ERROR,INFO,DEBUG,WARN)
How can I do that using shell script?

I have following lines

match => ["log_EventType", "ERROR"]
add_tag => [ "loglevelError" ]
if "loglevelError" in [tags] {

I want to changes these lines in

match => ["log_EventType", "DEBUG"]
add_tag => [ "loglevelDebug" ]
if "loglevelDebug" in [tags] {

What i have tried so far is:
match => ["log_EventType", "INFO"]

For this line I created a script

sed -i 's/"ERROR.*/"'$err'/' $file

and simply I run command ./ INFO

But in Output I get

match => ["log_EventType", "INFO

It does not return closing bracket after the word INFO

Answer Source

This script should solve your problem letting users specify any error level and have it replaced throughout the conf file regardless of which error level that was in the file in the first place:

sed -i 's/\(match => \["log_EventType", "\)[^"]*/\1'${err^^}'/g; s/\("loglevel\)[^"]*/\1'${err^}'/g' $file


$ ./ error
$ ./ debug


${1,,}, ${err^^} and ${err^} will take care of upper/lower case but might not work for bash versions before 4.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download