3

I'm using bash shell. I'm trying to write a script that will read a properties file and then do some replacements in another file based on the key-value pairs it reads in the file. So I have

#!/bin/bash

file = "/tmp/countries.properties"

while IFS='=' read -r key value
do
  echo "${key} ${value}" 
  sed -ie 's/:iso=>"${key}"/:iso=>"${key}",:alpha_iso=>"${value}"/g' /tmp/country.rb
done < "$file"

but when I go to run the file, I get a "Nno such file or directory error," despite the fact my file exists (I did an "ls" after to verify it).

localhost:myproject davea$ sh /tmp/script.sh 
=:                         cannot open `=' (No such file or directory)
/tmp/countries.properties: ASCII text
/tmp/script.sh: line 9: : No such file or directory
localhost:myproject davea$ 
localhost:myproject davea$ ls /tmp/countries.properties 
/tmp/countries.properties

What else do I need to do to read in my properties file successfully?

MikeD
  • 810
Dave
  • 2,548

2 Answers2

7

The errors are right there:

=:                         cannot open `=' (No such file or directory)

Something is trying to open a file called =, but it doesn't exist.

/tmp/script.sh: line 9: : No such file or directory

This would usually have the file name before the last colon, but since it's empty, it seems something is trying to open a file with an empty name.

Consider the line:

file = "/tmp/countries.properties"

That runs the command file with arguments = and /tmp/countries.properties. (The shell doesn't care what the arguments to a command are, there might be something that uses the equals sign as an argument.) Now, file just so happens to be a program used for identifying the types of files, and it does just that. First trying to open =, resulting in an error, and then opening /tmp/countries.properties, telling you what it is:

/tmp/countries.properties: ASCII text

The other No such file or directory comes from the redirection < $file. Since the variable isn't assigned a value, the redirection isn't going to work.

An assignment in shell requires that there be no white space around the = sign, so:

file=/tmp/countries.properties

Also, here:

sed -ie 's/:iso=>"${key}"/:iso=>"${key}",:alpha_iso=>"${value}"/g'

Variables aren't expanded within single quotes, and you have those around the whole second argument, so sed will get literal ${key} and not the contents of the variable.

Either end the single-quotes to expand the variables, or just use double-quotes for the whole string:

sed -ie 's/:iso=>"'${key}'"/:iso=>"'${key}'",:alpha_iso=>"'${value}'"/g' 
sed -ie "s/:iso=>\"${key}\"/:iso=>\"${key}\",:alpha_iso=>\"${value}\"/g"
ilkkachu
  • 138,973
0

Try:

file="/tmp/countries.properties"
phk
  • 5,953
  • 7
  • 42
  • 71
feeble
  • 27
  • 1