Q
Q
QQ2016-12-07 20:46:39
bash
QQ, 2016-12-07 20:46:39

How to find and replace the second occurrence?

Hello.
hello.txt

hello: ""
hello: ""
hello: ""

You need to insert into the second element.
hello: ""
hello: "world"
hello: ""

This code replaces the first occurrence.
sed -i "s/hello: \"\"/hello: \"world\"/" hello.txt
This code replaces all occurrences.
sed -i "s/hello: \"\"/hello: \"world\"/g" hello.txt

How to make only the second occurrence?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2016-12-07
@botaniQQQ

Something like this:
, where the colon is the definition of a label named a ;
N - add a new line to pattern space ;
$ - to the last line;
! - apply;
b - jump to label, in this case label a ;
s - search and replace;
/""/ - what we are looking for, in this case, empty quotes;
"world" - what to replace the found match with, in this case, "world" ;
/2 - replacement of the second match.

echo "hello: \"\"
hello: \"\"
hello: \"\"" | sed ':a;N;$!ba;s/""/"world"/2'

You can also try this option:
sed '2s/""/"world"/1'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question