I have assigned following string to a variable.
line="/remotepath/mypath/localpath/common/location.txt"
If I want to access common location (/remotepath/mypath/localpath/common) how can I split this in last "/" ?
I have assigned following string to a variable.
line="/remotepath/mypath/localpath/common/location.txt"
If I want to access common location (/remotepath/mypath/localpath/common) how can I split this in last "/" ?
In most unix-style operating systems, there's a program called dirname
which does this for you:
$ line="/remotepath/mypath/localpath/common/location.txt"
$ dirname "$line"
/remotepath/mypath/localpath/common
The command is of course available from any shell, since it's not part of the shell per-se, though you might need to assign the variable differently. For example, in csh/tcsh:
% setenv line "/remotepath/mypath/localpath/common/location.txt"
% dirname "$line"
/remotepath/mypath/localpath/common
If you want to strip off the file using shell commands alone, you'll need to specify what shell you're using, since commands vary. For example, in /bin/sh or similar shells (like bash), you could use "Parameter expansion" (look it up in the man page, there's lots of good stuff):
$ line="/remotepath/mypath/localpath/common/location.txt"
$ echo "${line%/*}
/remotepath/mypath/localpath/common
Hey you can use below command if your line variable contains same number of directories always
echo $line | cut -d "/" -f1-5
line="/remotepath/mypath/localpath/common/location.txt"
path="${line%/*}"
file="${line##*/}"
## contents of the variables after extraction
# path is '/remotepath/mypath/localpath/common'
# file is 'location.txt'
It's called parameter expansion/substring extraction in bash.