Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert text with sed on the same line that pattern search

Tags:

sed

For example if I have this file :

The green horse is blue localhost
my pants is dirty localhost
your eyes is so beautiful localhost
The best area is localhost

And I want to add text (192.168.25.50) in this file after each 'localhost' pattern search.

  • I don't want to create a new line
  • I don't want to insert on each end of line but just after a pattern
  • I don't want to use awk, I need to know if sed command can do this

Indeed my result must look like that :

The green horse is blue localhost 192.168.25.50
my pants is dirty localhost 192.168.25.50
your eyes is so beautiful localhost 192.168.25.50
The best area is localhost 192.168.25.50

Lot of sed issue exist but all have a specific context which can't help my simple and basics issue. I already can insert text after a pattern in a same file but never in a same line.

Can you explain me how to insert with sed command in a same line that the pattern used by sed command itself ?

like image 933
darkomen Avatar asked Feb 07 '16 10:02

darkomen


1 Answers

With GNU sed:

sed 's/\blocalhost\b/& 192.168.25.50/' file

\b: a zero-width word boundary

&: refer to that portion of the pattern space which matched

If you want to edit your file "in place" use sed's option -i.

like image 57
Cyrus Avatar answered Sep 21 '22 05:09

Cyrus