6

Let's say I have a string:

x=file.tar.sh

I know how to remove everything but last n-characters. Like this (removing everything but last 3 characters:

${x: -3}

But this doesn't work for files with different suffix lengths. (len .tar != len .sh)

I would tackle this by removing everything until the last dot. I've tried this:

${x##.}

This removes the longest matching until "." but somehow it just returns the full string without removing anything?

Jahid
  • 21,542
  • 10
  • 90
  • 108
mythic
  • 895
  • 2
  • 13
  • 31
  • your assignment is wrong should be this `x=file.tar.sh` – Azad May 11 '15 at 15:45
  • 1
    You seem to misunderstand what `${x##.}` should do. That will only remove a single leading period, and is identical to `${x#.}` since the given pattern only matches a single literal string. – chepner May 11 '15 at 16:13

1 Answers1

2

Try this:

x=file.tar.sh
echo ${x##*.}

This will print sh

If you want to get tar.sh, then:

echo ${x#*.}

Here * matches any set of characters before the occurrence of .

Jahid
  • 21,542
  • 10
  • 90
  • 108
  • Thanks, that works, but I don't understand the need for "*". Does it have to be used when using special characters? – mythic May 11 '15 at 16:11
  • 2
    What Jahid didn't explain was that he used **parameter expansion/substring extraction** to parse the line to remove the unwanted portions of the path. `##` starts from the left and then matches **all occurrences of pattern** `*.` (which says match everything up to the last `.`). The `*` is the wildcard for **zero or more occurrences of any character**. A single `#` matches **the first occurrence of pattern**. – David C. Rankin May 11 '15 at 16:20
  • Ok the only thing I really didn't get is the wildcard part. Thanks for clearing that up for me, I appreciate it. – mythic May 11 '15 at 16:26
  • @mythic http://www.linfo.org/wildcard.html – Jahid May 11 '15 at 16:31