1

I have a text file that contains references to variables and lets a user set up the formatting they want around variables, say something like

 The date is $DATE
 The time is $TIME

I then want to read this text file in, replace the variables, and print the result to stdout using a bash script. The closest thing I've gotten is using "echo" to output it,

 DATE="1/1/2010"
 TIME="12:00"
 TMP=`cat file.txt`
 echo $TMP

However, the output ends up all on one line, and I don't want to have \n at the end of every line in the text file. I tried using "cat << $TMP", but then there are no newlines and the variables inside the text aren't getting replaced with values.

3 Answers 3

3

You can use eval to ensure that variables are expanded in your data file:

DATE="1/1/2010"
TIME="12:00"
while read line
do
  eval echo ${line}
done < file.txt

Note that this allows the user with control over the file content to execute arbitrary commands.

If the input file is outside your control, a much safer solution would be:

DATE="1/1/2010"
TIME="12:00"
sed -e "s#\$DATE#$DATE#" -e "s#\$TIME#$TIME#" < file.txt

It assumes that neither $DATE nor $TIME contain the # character and that no other variables should be expanded.

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

Comments

0

Slightly more compact than Adam's response:

DATE="1/1/2010"
TIME="12:00"
TMP=`cat file.txt`
eval echo \""$TMP"\"

The downside to all of this is that you end up squashing quotes. Better is to use a real template. I'm not sure how to do that in shell, so I'd use another language if at all possible. The plus side to templating is that you can eliminate that "arbitrary command" hole that Adam mentions, without writing code quite as ugly as sed.

Comments

0

Just quote your variable to preserve newline characters.

DATE="1/1/2010"
TIME="12:00"
TMP=$(cat file.txt)
echo "$TMP"

For your modification of values in file with variables you can do -

while read -r line
do 
   sed -e "s@\$DATE@$DATE@" -e "s@\$TIME@$TIME@" <<< "$line"
done < file.txt

Test:

[jaypal:~/Temp] cat file.txt
The date is $DATE
The time is $TIME
[jaypal:~/Temp] DATE="1/1/2010"
[jaypal:~/Temp] TIME="12:00"
[jaypal:~/Temp] while read -r line; do sed -e "s@\$DATE@$DATE@" -e "s@\$TIME@$TIME@" <<< "$line"; done < file.txt
The date is 1/1/2010
The time is 12:00

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.