0

I've got a bash script that reads input from a file like this:

while IFS="|" read -r a b
do
   echo "$a something $b somethingelse" 
done < "$FILE"

The file it reads looketh like this:

http://someurl1.com|label1
http://someurl2.com|label2

However, I'd like to be able to insert the names of variables into that file when it suits me, and have the script process them when it sees them, so the file might look like this:

http://someurl1.com?$VAR|label1
http://someurl2.com|label2

So $VAR could be, for example, today's date, producing an output like this:

http://someurl1.com something label1 somethingelse
http://someurl2.com?20100320 something label2 somethingelse
2
  • 1
    But wouldn't that input produce a date before label1 and not before label2? Commented Mar 20, 2010 at 18:57
  • Yes, but that's OK. I want to add a variable to some of the lines not not all of them. Commented Mar 24, 2010 at 12:50

3 Answers 3

2

You might find this page useful. For the example you gave, try:

while IFS="|" read -r a b
do
    repl=`date +%Y%m%d`
    a=${a/\$VAR/$repl}
    echo "$a something $b somethingelse" 
done < "$FILE"

...though if the file format or language you're using aren't set in stone, there might be better alternatives ;)

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

Comments

1

Are you looking for something like this?

FILE=vexp.in
VAR=20100320
while IFS="|" read -r a b
do
   eval echo "$a something $b somethingelse"
done < "$FILE"

2 Comments

eval should be avoided for security reasons and this is a particularly good example. miorel's answer shows a way to narrow things down to handle only expected input.
Shell scripts should be avoided for security reasons, too, but we use them all the time. Not every question involves code injection vulnerability, and miorel's answer, while reasonable, does have the drawback of expanding only one specific variable and is still vulnerable to generic shell exploits so still shouldn't be used in a security context.
0

For a general solution that'll replace any environment variable (as well as execute any code, so don't use this if you don't control the variables or sanitize the input), use eval:

while IFS="|" read -r a b
do
  eval a=$a
  eval b=$b
  echo "$a something $b somethingelse" 
done < "$FILE"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.