tags:

views:

364

answers:

5

Given this variable in tcsh:

set i = ~/foo/bar.c

how can I get just the directory part of $i?

~/foo
+3  A: 

If your system provides a 'dirname' command you could:

set i = `dirname ~/foo/bar.c`
echo $i

Note the missing $ in front of the variable name. This solution is shell agnostic though.

ko-dos
A: 

Use dirname command, for example:

set i = `dirname "~/foo/bar.c"`

Notice the quotation marks around path. It's important to include them. If you skip the quotation marks, dirname will fail for paths which contain spaces. Mind that ~/ expression evaluates before dirname is executed, thus even such simple example may fail if quotation marks are not used and home path includes spaces.

Of course the same problem applies also to all other commands, it's good practice to always surround argument to a command with quotation marks.

Bartosz
A: 
echo $i | awk -F"/" '{$NF="";print}' OFS="/"
ghostdog74
+1  A: 

The way I found to do it while waiting for answers here:

set i = ~/foo/bar.c
echo $i:h

result:

~/foo
Nathan Fellman
A: 

For completely, getting the file name is accomplished with the basename command:

set j = `basename ~/foo/bar.c`
echo $j
Dr. Person Person II