Click here for important information about

problems getting last element in a directory string

October 5, 2012 at 04:51:37
Specs: Sun OS 5.8 Generic
I have a set of directory names from a file (variable length). I am a newbie to shell scripting (ksh) is what is used by my employer. Say I have a file called \node1\node2\node3. I need to be able to get the value node3 so that I can tar a file using that value.

See More: problems getting last element in a directory string

October 5, 2012 at 06:20:56
The basename command is what you are need. This is one of many links on this forum that describes the basename command and a shell scripting solutions:

Let me know if you have any further questions.


Report •

October 8, 2012 at 05:36:04
I tried a few of these and stll no luck. What I am doing is reading through a file line by line in a do loop. Each line has the full location of each directory that needs to be backed up. In the backup directory, I need to only use the last element on the filename to create a backup directory.
So I have a file called filelist.txt and it will have 1-n lines in it. I read this file and need to process each one to get for example /usr/programs/scripts/project. For this I just need to get projects into a separate variable to use.

Report •

October 8, 2012 at 07:17:42

while read myline
   myvar=$(basename $myline)
   echo $myvar
done < filelist.txt

Report •

Related Solutions

October 8, 2012 at 11:12:25
requirements have changed (don't they always). I am reading in a bunch of file directories from a file called filelist.txt. I don't have any issues with this. Each of the filenames can be variable length strings. I now need to break up each level into separate variables such that \\onedir\\twodir\\threedir\\fourdir need to be in separate variables so the value of
var1 = onedir
var2 = twodir
var3 = threedir
var4 = fourdir

Report •

October 8, 2012 at 15:56:03
Use eval to create dynamic variables:


while read myline
  eval var${counter}=$(basename $myline)
done < filelist.txt

echo $var1
echo $var2
echo $var3
echo $var4

# dynamically list out the $var variables
while [ "$num" -lt $counter ]
   eval echo \"\$var${num}\"

Report •

Ask Question