Home > Software design >  How to cut till the last delimiter and get remaining part of a string
How to cut till the last delimiter and get remaining part of a string

Time:04-08

I have a path ./test/test1 and I need to extract the test1 part.

I can do that with

cut -d '/' -f 3

But I may also have a path like ./test/test1/test1a in which case I need to extract the test1a part.

I can do this in a similar manner by switching 2, 3, 4 to suit my needs.

But how can I achieve this if I have a list which contains some paths.

./test/test1
./test/test1/test1a/
./test/test1/test1a/example

How can I always make sure I extract the last part of the string after the last / delimiter? How do I start cutting from the last string up till the delimiter?

EDIT: Expected output:

test1
test1a
example

CodePudding user response:

You can easily cut after the last delimiter, using awk, as you can see here:

cat conf.conf.txt | awk -F "/" '{ print $NF}'

(For your information: NF in awk stands for "Number of Fields".)

However, as the second line ends with a slash, the second result will be empty, as you see here:

test1

example

Is that what you want?

CodePudding user response:

path=./foo/bar/baz

basename "$path"

# or pure shell:
echo "${path##*/}"

Both return baz. The counterpart, dirname, returns ./foo/bar.

CodePudding user response:

It's not entirely clear what you mean by a "list". Perhaps you have the paths in an array, or just a space separated string. In either case, you can use basename, but the way you will use it depends on the data. If you have a space separated string, you can just use:

$ cat a.sh
#!/bin/sh

list='./test/test1
./test/test1/test1a/
./test/test1/test1a/example'

basename -a $list
$ ./a.sh
test1
test1a
example

That form will fail if there are characters in IFS in any of the names. If you have the names in an array, it is slightly easier to deal with that issue:

#!/bin/sh

list=('./test/with space/test1'
./test/test1/test1a/
./test/test1/test1a/example)

basename -a "${list[@]}"
  • Related