Search code examples
bashfilevariablesfile-manipulation

Bash: how to process variables from an input file?


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

Solution

  • 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 ;)