Issue
I have below data in file
They used to carry lots of treats
but now they don’t have any sweets.
And so, if you’re in need of candy,
please don’t visit Mrs. Mandy. He is working in office.But will be late from office
For example :
using this following command i got the line which as both keywords in same line
grep "Mandy" file.txt | grep "office"
The above command as given me below line as output
please don’t visit Mrs. Mandy. He is working in office.But will be late from office
Now from above line which i got as an output need to delete second occurrence keyword : office
and print below output
Expected output :
please don’t visit Mrs. Mandy. He is working in office.But will be late from
How to achieve the above expected output ?
Solution
sed
can do that using s/office//2
. On top of that, you can combine the entire pipeline into a single command.
sed -n '/Mandy/s/office//2p' file.txt
Explanation:
In above command there are 2 sed
commands.
/Mandy/
runs the next command only on lines containingMandy
.s/office//2p
deletes (substitute with the empty string) the 2nd occurrence ofoffice
in those lines and prints them afterwards.
Answered By - Socowi