-1

I want to replace a line in a text file with 3 variables. The search keyword is also a variable.

Also, I need 2 spaces between each variable.

I tried the following code:

sed -i -e 's/'"$keyword"'/'"$var1"' '"$var2"' '"$var3"'/' file.txt

sed -i -e 's/"$keyword"/"$var1" "$var2" "$var3"/' file.txt

sed -i -e "s/$keyword/$var1 $var2 $var3/" file.txt

Let's say that the file is:

Banana Apple Pear
America Spain Italy

So, by searching America, I want the following result:

Banana Apple Pear
$var1 $var2 $var3
Eduardo Baitello
  • 10,469
  • 7
  • 46
  • 74
  • I think what you have at the moment will probably generate `$var1 $var2 $var3 Spain Italy` You will need to add extra arguments to the search part to collect all the fields you want to replace. – Gem Taylor Apr 02 '19 at 16:24

1 Answers1

1

It should not be complicated than

var1=Orange
var2=Grape
var3=Fig
text=America

sed "/${text}/{s/^.*$/${var1}  ${var2}  ${var3}/}" filename

Output

Banana Apple Pear
Orange  Grape  Fig

The key is using double quotes so that bash variables will be expanded. Note that this variable expansion happens before sed processing starts.

To replace the whole line ^.*$ should be used, which says from the start(^), select any character(.) that occur any number of times (*) till the end($).

sjsam
  • 21,411
  • 5
  • 55
  • 102
  • I'm really baffled this was accepted. Is the question wrong or does this answer just happen to do something else than the OP asked for in a way which looks like it's working? – tripleee Apr 03 '19 at 06:49
  • @tripleee : I believe the first line in the question `I want to replace a (pattern matched) line in a text file with 3 variables` summarizes the question well. Did I miss something there? – sjsam Apr 03 '19 at 07:11
  • The expected output in the question does not match what you report as the result. Also, there should be two spaces between the replacements. But perhaps the real problem is that the question is astonishingly unclear. – tripleee Apr 03 '19 at 07:14
  • @tripleee Clearly, the op wants the substitutions in the expected output. I am pretty sure coz this is the accepted answer :-). Taking into account the extra space you mentioned. Thank you. – sjsam Apr 03 '19 at 07:18
  • @tripleee Well, after that edit, I do feel the same sentiments expressed by you. But being nice, because the op is a new contributor.. – sjsam Apr 03 '19 at 07:21
  • Sure -- let's leave it at that. – tripleee Apr 03 '19 at 07:22