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

Report •

#1
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:

http://www.computing.net/answers/un...

Let me know if you have any further questions.

nails


Report •

#2
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 •

#3
October 8, 2012 at 07:17:42
#!/bin/ksh

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


Report •

Related Solutions

#4
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 •

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

#!/bin/ksh

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

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

# dynamically list out the $var variables
num=1
while [ "$num" -lt $counter ]
do
   eval echo \"\$var${num}\"
   ((num+=1))
done


Report •

Ask Question