3

we have the following file:

more /tmp/file

Allow,Deny
Allow,Deny

we want to change only the second match word ( to replace Allow,Deny with Deny,Allow )

so we did

sed 's/Allow,Deny/Deny,Allow/1'  /tmp/file

Deny,Allow
Deny,Allow

but it replace both them

while the expected results:

Allow,Deny
Deny,Allow

how to replace only the second ,match word

2 Answers 2

3

Another sed solution.

sed '0,/Allow/!{0,/Allow/s/Allow/Deny/}' /tmp/file

Here we match the first Allow then we ignore the substitution for the first Allow we come across and substitute the next line.

To give an idea, the following would substitute the second and fourth since we used N;

sed '0,/Allow/!{N;/Allow/s/Allow/Deny/}'

Or using awk:

awk '/Allow/{c++; if (c==2) { sub("Allow","Deny")}}1'

We match Allow then keep a counter c. If this matches the 2 second occurrence then we substitute it.

2

to change only the second match word ( to replace Allow,Deny with Deny,Allow )

sed solution:

Sample tmp_file:

Allow,Deny
Allow,Deny
Allow,Deny
Allow,Deny

sed ':a;N;$!ba; s/Allow,Deny/Deny,Allow/2' tmp_file

The output:

Allow,Deny
Deny,Allow
Allow,Deny
Allow,Deny

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.