0

I am writing a shell script in which I have to separate the file name and file path from a complete file path. For example /home/loneranger/Documents/test/file.dat is the complete path. I want to separate name and Path and put them in variables. So far I am able to separate file name by using basename command.

file_name =$(basename $path) 
file_location =`echo $path | sed 's/$file_name//' `

But the sed command is not working. It's working when I execute it outside in command line by replacing the file_name by file.dat. Not sure why it's behaving this way. Can somebody explain.

PS: Sorry for poor formatting as I am typing from a mobile device.

Lesmana
  • 25,663
  • 9
  • 82
  • 87
redsoxlost
  • 1,215
  • 5
  • 19
  • 32
  • possible duplicate of [sed substitution with bash variables](http://stackoverflow.com/questions/7680504/sed-substitution-with-bash-variables) – tripleee Jun 15 '14 at 06:37

2 Answers2

4

the tool dirname does what you want:

file_name=$(basename $path)
file_location=$(dirname $path)

the sed command is not working because bash does not expand variables inside single quotes.

sed 's/$file_name//'
    ^ single quote
       ^ variable inside single quote not expanded

either use double quotes or open the single quotes around the variable:

sed "s/$file_name//"
sed 's/'$file_name'//'

but as said the tool dirname does what you want.

also note that you may not put spaces around the equal sign in the variable assignment

file_name =$(basename $path)
         ^ there should be no space here

the line above does not assign the result of basename to the variable file_name. instead it will try to execute the command file_name with one parameter which is the result of basename.

file_name=$(basename $path)
         ^ no space here

this line will define the variable.

Lesmana
  • 25,663
  • 9
  • 82
  • 87
0

It isn't working because you use $file_name in simple quote ('). Use double quotes " for enable variable translation.

file_location =`echo $path | sed "s/$file_name//"
Zulu
  • 8,765
  • 9
  • 49
  • 56