Home > Enterprise >  Replace a line if previous lines match
Replace a line if previous lines match

Time:09-25

I'm trying to write a bash script but I'm currently stuck.

Let's say i have the following file:

targets {
        type = pppcfg_target_internet;
        name = "internet";
        only_crypt_auth = no;
        local {
                username = "";
                passwd = "";

I would like to replace the username and password. The problem is, this section exists multiple times, except for the second line.

So what I would like to do:

Replace "username" and "password" if there is a "type = pppcfg_target_internet;" a few lines before.

Preferably, I'd like to keep it flexible enough that I don't have to set it to the exact line in case the code changes a bit or a line gets added.

So "If there is "pppcfg_target_internet" in the 5-10 lines above the searched string, replace "password" and "username".

I will be glad to receive any help. Also for the recommendation whether to use "ask" or "sed".

CodePudding user response:

You can use sed to choose range of text between specific lines where you want to replace, like the following

sed '/pppcfg_target_internet/,/}/s/passwd.*/passwd = "newpass"/g'

This means, that between strings with "pppcfg_target_internet" and "}" find and replace string starting with passwd with the next string: 'passwd = "newpass"'

Maybe it would be good to create some unique block ending

CodePudding user response:

This might work for you (GNU sed):

sed -E '/type = pppcfg_target_internet;/{:a;N;/passwd/!ba
        s/(username = ).*/\1"new user";/m;s/(passwd = ).*/\1"new pass";/m}' file

Gather up lines between type = pppcfg_target_internet; and passwd and then substitute new user and password values.

N.B. The use of the m flag on the substitute command to assure the substitution only occurs for that matching line.

  • Related