views:

80

answers:

4

I am trying to become more familiar with using the builtin string matching stuff available in shells in linux. I came across this guys posting, and he showed an example

a="abc|def"
echo ${a#*|}    # will yield "def"
echo ${a%|*}    # will yield "abc"

I tried it out and it does what its advertised to do, but I don't understand what the $,{},#,*,| are doing, I tried looking for some reference online or in the manuals but I couldn't find anything. Can anyone explain to me what's going on here?

+1  A: 

Take a look at this.

${string%substring}

Deletes shortest match of $substring from back of $string.

${string#substring}

Deletes shortest match of $substring from front of $string.

EDIT:

I don't understand what the $,{},#,*,| are doing

I recommend reading this

nc3b
+3  A: 

This article in the Linux Journal says that the # operator deletes the shortest possible match on the left, while the % operator deletes the shortest possible match on the right.

So ${a#*|} returns everything after the |, and ${a%|*} returns everything before the |.

If you had a situation that called for greedy matching, you'd use ## or %%.

Mark Rushakoff
+1  A: 

Typically, ${somename} will substitute the contents of a defined parameter:

mystring="1234567"
echo ${mystring}    # produces '1234567'

The % and # symbols are allowing you to add commands that modify the default behavior.

The asterisk '*' is a wildcard; while the pipe '|' is simply a matching character. Let me do the same thing using the matching character of '4'.

mystring="1234567"
echo ${mystring#*4}  # produces '567'
Fred Haslam
+1  A: 

Those features and other similarly useful ones are documented in the Shell Parameter Expansion section of the Bash Reference Manual. Here's another really good reference.

Dennis Williamson