miltone
miltone

Reputation: 4721

insert text with sed on the same line that pattern search

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.

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 ?

Upvotes: 12

Views: 37862

Answers (1)

Cyrus
Cyrus

Reputation: 88573

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.

Upvotes: 29

Related Questions