Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
237 views
Welcome To Ask or Share your Answers For Others

1 Answer

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($).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...