0

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 "/" ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
User19792255
  • 111
  • 2
  • 10
  • 1
    To give you a good answer please be more accurate: Which OS and shell do you use? – UsersUser Apr 29 '15 at 10:36
  • Add this after your line: `echo $line | sed 's/.\{13\}$//'`. This command removes last 13 characters from the string. – Rajesh N Apr 29 '15 at 11:02
  • @UsersUser - the operating system doesn't matter much. The shell though... – ghoti Apr 29 '15 at 11:38
  • possible duplicate of [Grab the filename in Unix out of full path](http://stackoverflow.com/questions/10124314/grab-the-filename-in-unix-out-of-full-path) – Jahid Apr 29 '15 at 11:59

3 Answers3

1

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
ghoti
  • 45,319
  • 8
  • 65
  • 104
1

Hey you can use below command if your line variable contains same number of directories always

echo $line |  cut -d "/" -f1-5
Murli
  • 1,258
  • 9
  • 20
0
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.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85