Benson
Benson

Reputation: 11

Replace a pattern on every second occurence using variables

Hi guys I need help using linux script.

This is a sample input:

Login=Testtt/123 Password=Testtt/123 Login=eJwQwq12 Password=OjeEor/Kd

First I searched the pattern using grep then awk using the following code

passStr=grep 'Passsword' test.param | awk -F= '{print $2}'

So there I got the Testtt123 then put it into the variable using passStr.

Then I put the replacement string into another variable using

passNew=ThisIsATest=

Now I need to replace the second occurrence of string called Testtt123 which is in passStr and replace it into ThisIsATest= using the variable passNew

I only have this code but it replaces all occurrence of the string.

sed /$passStr/{s/$passStr/$passNew/} test.param

The problem here is that the second occurrence lies on different lines. There are other occurences of Password which makes it hard for me to use awk because the passStr will have two possible values. I only need the first Password.

Next is that there are times in which the value of the Password contains slashes.(changed the sample input)

The output should go like

Login=Testtt123 Password=ThisIsATest= Login=eJwQwq12 Password=OjeEor/Kd

Any help I can get?

Upvotes: 0

Views: 65

Answers (2)

glenn jackman
glenn jackman

Reputation: 247022

You're over-complicating with "2nd occurrance". Just search for "Password" and replace what's after the "="

sed '/Password/ s/=.*/='"$passNew"/' file

Upvotes: 0

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed "$!N;$s/${passStr}/${passNew}/2" test.param

sed is line by line by default, you need to load first the content into the working buffer and make the test at the last line loaded

Upvotes: 1

Related Questions