I've some notes of useful regular expressions and one that I always use is the following:
echo '/home/user/folder/file.txt' | sed -E 's/[\\\/][^\\\/]*$//g'
The result that I get from this regular expression is the path of the parent folder /home/user/folder
. I understand the basics of regular expressions with:
\s # all white space
\S # no white space
. # all chars
\. # period
+ # sequence of once or more
{5} # sequence of delimited interval
* # sequence of zero or more
? # sequence of once or none
[0-9] # any sequence of number
[a-z] # any sequence of letter
[^x-y] # no sequence of letter
^ # beginning
$ # ending
However, I haven't managed to figure out what is the meaning of [\\\/]
and [^\\\/]
in the case of the regular expression from my example. How does it work?
sed 's#\(.*\)/.*#\1#'
orsed 's#/[^/]*$##'
, or use thedirname
utility? – Kusalananda Apr 15 '22 at 05:51sed 's#\(.*\)/.*#\1#'
andsed 's#/[^/]*$##'
better thansed 's/[/][^/]*$//'
? I made this question because I was struggling to understand that regular expression. It wasn't so much about solving the problem of gettingdirname
. Multiple times I made a mess onbash
code because I was usingdirname
ofdirname
ofdirname
... The code can get ugly like that. – raylight Apr 15 '22 at 06:15dirname
does not help with that. In thezsh
shell, it would be a simple matter of using$pathname:h
,$pathname:h:h
etc. – Kusalananda Apr 15 '22 at 06:30[\\\/]
was out of it... I missed the concept that[abc]
isa
orb
orc
as explained in the accepted answer... So I wasn't understanding that it was just \ or / in the end. – raylight Apr 15 '22 at 06:33