LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   reading path from a text file using bash script (https://www.linuxquestions.org/questions/linux-newbie-8/reading-path-from-a-text-file-using-bash-script-651987/)

mksc 06-27-2008 02:51 AM

reading path from a text file using bash script
 
hi all

I have a text file which consist file names with complete path.
I want a script which takeout path of file one by one and store path in a variable and file name in other variable.

i am giving you some part of this text file:

/root/Documents/ListOfnts.ods
/root/Documents/NewCmpnDet.xls
/root/Documents/ComTstChkLst.ods
/root/Documents/compstat.ods
/root/Documents/PDF BOOKS/handbook.pdf
/root/Documents/200804A0/04042008944.jpg
/root/Documents/printer/steps.txt
/root/Documents/AC97/bus.h


with the help of script I want output like this
PATH=/root/Documents/
FILE=ListOfnts.ods


Thanks
MKSC

druuna 06-27-2008 03:21 AM

Hi,

You could use the basename and dirname commands to split directories from filenames. The first one (basename) will strip the dir part, the other one does the opposite:

Quote:

myPath="/root/Documents/ListOfnts.ods"

$ echo myPath
/root/Documents/ListOfnts.ods

$ basename $myPath
ListOfnts.ods

$ dirname $myPath
/root/Documents
A simple onliner to show it in action, using your example:
Code:

$ for THIS in `cat infile`
> do
> echo $THIS
> DIRNAME=$(basename $THIS)
> echo $DIRNAME
> FILENAME=$(dirname $THIS)
> echo $FILENAME
> done

/root/Documents/ListOfnts.ods
ListOfnts.ods
/root/Documents

/root/Documents/NewCmpnDet.xls
NewCmpnDet.xls
/root/Documents

/root/Documents/ComTstChkLst.ods
ComTstChkLst.ods
/root/Documents

Hope this helps.

colucix 06-27-2008 03:25 AM

You can either use the dirname and basename commands into a loop which reads the file line by line, or use the following parameter substitution:
Code:

P=${line%/*}
F=${line##*/}

where $line is the current line read from the file.

An aside note: don't use PATH as name of a variable in your script, since it is a reserved word for the environment variable PATH. If you change its value inside your script, most likely you will get "Command not found" errors for subsequent statements.


All times are GMT -5. The time now is 08:01 PM.