preethy tulpi
preethy tulpi

Reputation: 415

Search string and add string at end of line but before quotes using sed

I am seeking help to find string and add string in end of line but before quotes

file output:

 I have a file
 search_string="It has some text"
 some other text

I tried below method:

 sed -i '/^search_string=/ s/$/ add_string one add_string two/' file

I am getting below output:

 I have a file
 search_string="It has some text" add_string one add_string two
 some other text

expected output:

 I have a file
 search_string="It has some text add_string one add_string two"
 some other text

Upvotes: 2

Views: 2252

Answers (3)

Sundeep
Sundeep

Reputation: 23707

simple modification to OP's code

$ sed '/^search_string=/ s/"$/ add_string one add_string two"/' file
I have a file
search_string="It has some text add_string one add_string two"
some other text
  • "$ match double quotes at end of line
  • in replacement section, add the quote as well

Or to avoid repeating text for longer text, use &. For example:

$ sed '/^search_string=/ s/ text"$/ add_string one add_string two&/' file
I have a file
search_string="It has some add_string one add_string two text"
some other text

Upvotes: 0

Marc Lambrichs
Marc Lambrichs

Reputation: 2892

$ sed 's/search_string="[^"]*/& add_string_one add string two/' file

You can do it in-place, with -i:

$ sed -i.bak 's/search_string="[^"]*/& add_string_one add string two/' file

$ diff file.bak file
2c2
< search_string="It has some text"
---
> search_string="It has some text add_string_one add string two"

Upvotes: 4

CWLiu
CWLiu

Reputation: 4043

sed '/^.*search_string=/ s/\(.*\)"/\1 add_string one add_string two"/' file

Upvotes: 0

Related Questions