LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Bash - String replace at the end with a regex (https://www.linuxquestions.org/questions/linux-general-1/bash-string-replace-at-the-end-with-a-regex-904930/)

myro 09-25-2011 12:38 PM

Bash - String replace at the end with a regex
 
Hi,
I want to remove the last foldername in a string variable:
"hello/mr/robinson/"
should become
"hello/mr/"

I am trying it the following way:

a="hello/mr/robinson/"
echo ${a//[^\/]*\/$/}

But it seems that ${} does not recognize $ as end of string delimiter.
Any ideas?

cheesus 09-25-2011 01:04 PM

Hello, how about
dirname $a
Cheers, Tom.

myro 09-25-2011 01:21 PM

Quote:

Originally Posted by cheesus (Post 4481879)
Hello, how about
dirname $a
Cheers, Tom.

thanks. this works in that example, but it would still be nice to know what kind of regex are useable in ${} expressions. Also, the dirname solution seems to be slower than a ${} expression.

myro 09-25-2011 01:34 PM

I also just noticed that with dirname I will get a ".", if I have "hello/" for example. But I want that to become ""

crts 09-25-2011 02:50 PM

Quote:

Originally Posted by myro (Post 4481867)
Hi,
I want to remove the last foldername in a string variable:
"hello/mr/robinson/"
should become
"hello/mr/"

I am trying it the following way:

a="hello/mr/robinson/"
echo ${a//[^\/]*\/$/}

But it seems that ${} does not recognize $ as end of string delimiter.
Any ideas?

Hi,

try this:
Code:

echo ${a##${a%%*([^/])/}}
This will only work if your path does end with a slash '/'.

A few more notes:
The part in bold is called an extended pattern. You might have to set it in bash before you can use it:
Code:

shopt -s extglob
It is NOT a RegEx. Bash does not recognize RegEx within String manipulation. Therefore your '$' at the end does not work as you expected it to.

Hope this helps.

myro 09-25-2011 02:59 PM

Quote:

Originally Posted by crts (Post 4481942)
Hi,

try this:
Code:

echo ${a##${a%%*([^/])/}}

thanks a lot:
Code:

echo ${a%%*([^/])/}
got me the result I wanted.

crts 09-25-2011 03:34 PM

Oops
 
Quote:

Originally Posted by myro (Post 4481945)
thanks a lot:
Code:

echo ${a%%*([^/])/}
got me the result I wanted.

Somehow I misread you first post and I thought you just wanted the last part to keep. Well, glad you filtered out the useful part of my suggestion.

David the H. 09-27-2011 04:37 PM

parameter expansions don't use regular expressions, they follow shell globbing rules.

Don't forget that you can also add characters back to the string after expansion, which may help simplify things in some places. To retain the following backslash on "/hello/mr/", for example, you could simply do this:
Code:

a="hello/mr/robinson/"
echo "${a%/*/}/"



All times are GMT -5. The time now is 11:33 PM.