user2693845
user2693845

Reputation:

how to get a substring with varied length?

So i am writing a script which gets the substring from the input which is a path to a file (/path/to/file.ext) and if the directory (/path/to) does not exist it will run mkdir -p /path/to and then touch file.ext.

my question is this, how can i use cut to get the /path/to if we have a potentially unknown length of /'s

my script currently looks like this

INPUT=$0
SUBSTRING_PATH=`$INPUT | cut -d'/' -f 2`

if [! -d $SUBSTRING_PATH]; then
    mkdir -p $SUBSTRING_PATH
fi

touch $INPUT

Upvotes: 1

Views: 73

Answers (1)

Wintermute
Wintermute

Reputation: 44023

Instead of cut, use dirname and basename:

input=/path/to/foo
dir=$(dirname "$input")
file=$(basename "$input")

Now $DIR is /path/to and $FILE is foo.

dirname will also give you a valid directory for relative paths to the working directory (I mean that $(dirname file.txt) is .). This means, for example, that you can write "$dir/some/stuff/foo" without having to worry that you end up in a completely different directory tree (such as /some/stuff rather than ./some/stuff).

As @ruakh mentions in the comments, if you didn't have a directory but a string of tokens of which you wanted to discard the last (a line of a csv file, perhaps), one way to do it would be "${input%,*}", where the comma can be replaced by any delimiter. To my knowledge this is a bash extension. I only edit this in because a stray visitor in the future might have better luck seeing it here than in the comments; for your particular use case, dirname and basename are a better fit.

Upvotes: 4

Related Questions