Khalid
Khalid

Reputation: 21

Append a string to every matching pattern starting with some characters

I'm trying to append a string '_SOMETHING' to every existing string in a file starting with 'check_nrpe_aix' using awk or sed

Before :

define command {
        command_name    check_nrpe_aix_load
        command_line    $USER1$/check_nrpe -p $USER11$ -H $HOSTADDRESS$ -a $ARG1$ $ARG2$ ARG3$
        }

define command {
        command_name   check_nrpe_aix_cpu_stats
        command_line    $USER1$/check_nrpe -p $USER11$ -H $HOSTADDRESS$ -a $ARG1$ $ARG2$
        }

After :

define command {
        command_name    check_nrpe_aix_load_SOMESTRING
        command_line    $USER1$/check_nrpe -p $USER11$ -H $HOSTADDRESS$ -a $ARG1$ $ARG2$ ARG3$
        }

define command {
        command_name   check_nrpe_aix_cpu_stats_SOMESTRING
        command_line    $USER1$/check_nrpe -p $USER11$ -H $HOSTADDRESS$ -a $ARG1$ $ARG2$
    }

Upvotes: 0

Views: 736

Answers (2)

potong
potong

Reputation: 58488

This might work for you (GNU sed):

sed 's/\<check_nrpe_aix\S*/&_SOMETHING/g' file

Append _SOMETHING to any word beginning check_nrpe_aix.

Upvotes: 0

dsaravel
dsaravel

Reputation: 11

I placed your example in a file named input.txt

$ cat input.txt 
define command {
        command_name    check_nrpe_aix_load
        command_line    $USER1$/check_nrpe -p $USER11$ -H $HOSTADDRESS$ -a $ARG1$              $ARG2$ ARG3$
        }

define command {
        command_name   check_nrpe_aix_cpu_stats
        command_line    $USER1$/check_nrpe -p $USER11$ -H $HOSTADDRESS$ -a $ARG1$ $ARG2$
        }

Now if you run :

awk 'BEGIN {OFS=""} {if ($0 ~ /check_nrpe_aix/) print $0,"_SOMESTRING";else print $0}' input.txt

you should get the result you expected:

$ awk 'BEGIN {OFS=""} {if ($0 ~ /check_nrpe_aix/) print $0,"_SOMESTRING";else print $0}' input.txt
define command {
        command_name    check_nrpe_aix_load_SOMESTRING
        command_line    $USER1$/check_nrpe -p $USER11$ -H $HOSTADDRESS$ -a $ARG1$ $ARG2$ ARG3$
        }

define command {
        command_name   check_nrpe_aix_cpu_stats_SOMESTRING
        command_line    $USER1$/check_nrpe -p $USER11$ -H $HOSTADDRESS$ -a $ARG1$ $ARG2$
        }

Breaking it down:

OSF is the output field separator. I set it to empty so it doesn't add a space when appending the "_SOMESTRING" to the line

The command

if ($0 ~ /check_nrpe_aix/) print $0,"_SOMESTRING";

will search for the "check_nrpe_aix" expression and print the whole line ($0) plus "_SOMESTRING" separated by OSF

The command ;else print $0}

will print the whole line without alterations if it doesn't match the condition of the previous command

Upvotes: 1

Related Questions