I need a script to be able to take a path such as "/foo/bar/thing" a put the "/foo/bar/" bit in one variable and the "thing" bit in another.
I figured awk would probably be the best tool for the job but looking at the man page didn't seem to help. The only way i know how to use awk is with '{print $1, $2 ,$3}' but that doesn't help unless i can get it to count from the end of the string.
use basename to get the file name
and dirname to get the path.
program=/this/is/the/path/to/my/file.ksh
FILE=$(basename program)
DIR=$(dirname program)
echo $FILE
file.ksh
echo $DIR
/this/is/the/path/to/my
Dont use this code since its better to use built-ins rather than
writing something like this, but, here is a method in Awk to
get the parent directory of a file.
echo $PARENT_PATH | awk ' {
arraySize = split($0, parentPath, "/");
delete parentPath[arraySize];
for (i in parentPath ) {
w = w "/" parentPath;
}
print w
}'
In short the code for 'path' will print everything before the last /
The code for 'filename' will print eveything after the last /
It doesnt matter how many sub directories you have in the path name, it will always work.
Try it, Its probably one of my most used pieces of code!
I would need a basename like action (or the '##*/') but probably in combination with awk.
I need it to transform ftp commandfiles from put to get syntax.
If this is the original file :
open 10.1.91.15
user caluwaek xxxxxxx
cd /export/home/caluwaek/ftp
put /export/home/caluwaek/ftp_bestanden/bestand.txt
put /export/home/caluwaek/ftp_bestanden/bestand2.txt bestand2_copy.txt
bye
I use sed to change put in get, as wel as to change the filenames from left to right. Result :
open 10.1.91.15
user caluwaek cindy75
cd /export/home/caluwaek/ftp
get /export/home/caluwaek/ftp_bestanden/bestand.txt
get bestand2_copy.txt /export/home/caluwaek/ftp_bestanden/bestand2.txt
bye
The only thing that remains to do is to drop the paths. Only on the lines which start with get and only if the file is on the right side.
$ cat file1
open 10.1.91.15
user caluwaek cindy75
cd /export/home/caluwaek/ftp
put /export/home/caluwaek/ftp_bestanden/bestand.txt
put /export/home/caluwaek/ftp_bestanden/bestand2.txt bestand2_copy.txt
bye
$ awk 'sub(/put/,"get",$1)&&$3{x=$2;$2=$3;$3=x};1' file1 > file2
$ cat file2
open 10.1.91.15
user caluwaek cindy75
cd /export/home/caluwaek/ftp
get /export/home/caluwaek/ftp_bestanden/bestand.txt
get bestand2_copy.txt /export/home/caluwaek/ftp_bestanden/bestand2.txt
bye