cr1zz
cr1zz

Reputation: 577

Bash - Split dir string

I got the following string: '/transfer/IN/name/test.txt'

Now I'm trying to split this for the string name, cause I need it for further operations.

How can I split this correctly?

I've tried with cut (would sed be better?), but I'm not able to find the right approach.

Thanks for your help in advance.

Upvotes: 2

Views: 68

Answers (3)

choroba
choroba

Reputation: 241828

You can use Parameter expansion:

#!/bin/bash

path=/transfer/IN/name/test.txt
path1=${path%/*}           # Remove everything from the last /.
path1=${path1##*/}         # Remove everything up to the last /.
echo "$path1"

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

Just use the proper tools dirname and basename chained together:

echo $(basename $(dirname /transfer/IN/name/test.txt))
  • dirname => /transfer/IN/name
  • basename => name

sed solution looks more complex BTW:

 sed -e "s#.*/\([^/]*\)/[^/]*#\1#" -e "s#/.*##" <<< name/test.txt

(2 expressions to handle the full relative case name/test.txt)

Upvotes: 1

Kent
Kent

Reputation: 195039

This should help too:

awk -F'/' '{print $(NF-1)}' <<<"/a/b/c/d"

And it outputs:

c

If you like using sed:

sed 's#/[^/]*$##;s#.*/##' <<<"/a/b/c/d"

Upvotes: 2

Related Questions