-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
1
  • 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. Commented Apr 2, 2019 at 16:24

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

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 : 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?
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 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.
@tripleee Well, after that edit, I do feel the same sentiments expressed by you. But being nice, because the op is a new contributor..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.