Scott
Scott

Reputation: 37

Regex matching filenames

I Know this will sound silly to some of you but I am not good with regex resolutions. I came across the following expressions in a function someone else has written and can't figure out what he/she was doing.

REGEX 1

[ ! -d ${2%/*}/ ]

REGEX 2

cmp -s $2 ${2##*/}

as you can guess, these regex evaluations are being used in a script, doing file updating and moving them around. I was wondering the meaning of

${2%/*}/ 

and

${2##*/}

Upvotes: 2

Views: 93

Answers (1)

anubhava
anubhava

Reputation: 785156

Let's take an example to understand better:

s='abc/def/foo'
echo "${s%/*}/"
abc/def/

echo "${s##*/}"
foo
  1. First expression is discarding text after last / in the input.
  2. Second expression is discarding all the text before last / in the input.

You can see more details in man bash:

  • ##*/ is used to match longest string before / from start of input string.
  • %/* is used to match text after / from end of input.

Upvotes: 4

Related Questions