Maheen Nasir Maheen Nasir - 3 months ago 10
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?

Example
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

file=xyz.conf
err=$1
sed -i 's/"ERROR.*/"'$err'/' $file


and simply I run command ./script.sh INFO

But in Output I get

match => ["log_EventType", "INFO


It does not return closing bracket after the word INFO

Answer

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:

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

Examples:

$ ./script.sh error
$ ./script.sh debug

Note:

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

Comments