0

I am trying to read a variable value from test.sh and write it in file2.txt by replacing the word COMP in file2.txt

I am using below command to achieve this but not possible

sed -r 's/(echo "$NAME" test.sh)/COMP/' file2.txt

for your reference

test.sh contains

#!/bin/bash
NAME=RAJ

2 Answers 2

1

To read variables from a file you can use the source or . command. Then use double quotes to make the shell expand variables while preserving whitespace:

source test.sh && sed -i "s/$NAME/COMP/g" file2.txt

The BSD sed command takes the -i option but requires a suffix for the backup (but an empty suffix is permitted). So if you’re running on Mac or BSD system, use:

source test.sh && sed -i '' "s/$NAME/COMP/g" file2.txt
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your answer @1218985, but its not working. i expect to achieve in single line command
can you suggest me the answer like in following format sed -i "s/(source test.sh | $NAME )/COMP/g" file2.txt
@k4jc You can do source test.sh && sed -i "s/$NAME/COMP/g" file2.txt if you need a one liner
thank you, can i use the source command, if i have multiple variables in test.sh file and all these variable values to be written in .txt file
1

You've got your sed s/// backwards, I think. You want to search for COMP and replace the value of $NAME

. test.sh
sed "s/COMP/$NAME/" file2.txt

If $NAME can contain a slash character, it will break sed's s/// command, so you need to escape slashes in the variable expansion

. test.sh
replacement=${NAME//\//\\\/}
sed "s/COMP/$replacement/" file2.txt

# NAME='a/b/c/d'
# echo "${NAME//\//\\\/}"    # => a\/b\/c\/d

Comments

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.