Skip to main content
  1. About
  2. Stack Internal
The 2026 Annual Developer Survey is live— take the Survey today!
added 38 characters in body
Source Link
phil294
  • 11.1k reputation score 11115
  • 8
  • 8 gold badges
  • 75
  • 75 silver badges
  • 113
  • 113 bronze badges

If you also want to allow empty extensions, this is the shortest I could come up with:

echo 'hello.txt' | sed -r 's/.+\.(.+)|.*/\1/' # EXTENSION
echo 'hello.txt' | sed -r 's/(.+)\..+|(.*)/\1\2/' # FILENAME

1st line explained: It matches PATH.EXT or ANYTHING and replaces it with EXT. If ANYTHING was matched, the ext group is not captured.

If you also want to allow empty extensions, this is the shortest I could come up with:

sed -r 's/.+\.(.+)|.*/\1/' # EXTENSION
sed -r 's/(.+)\..+|(.*)/\1\2/' # FILENAME

1st line explained: It matches PATH.EXT or ANYTHING and replaces it with EXT. If ANYTHING was matched, the ext group is not captured.

If you also want to allow empty extensions, this is the shortest I could come up with:

echo 'hello.txt' | sed -r 's/.+\.(.+)|.*/\1/' # EXTENSION
echo 'hello.txt' | sed -r 's/(.+)\..+|(.*)/\1\2/' # FILENAME

1st line explained: It matches PATH.EXT or ANYTHING and replaces it with EXT. If ANYTHING was matched, the ext group is not captured.

Source Link
phil294
  • 11.1k reputation score 11115
  • 8
  • 8 gold badges
  • 75
  • 75 silver badges
  • 113
  • 113 bronze badges

If you also want to allow empty extensions, this is the shortest I could come up with:

sed -r 's/.+\.(.+)|.*/\1/' # EXTENSION
sed -r 's/(.+)\..+|(.*)/\1\2/' # FILENAME

1st line explained: It matches PATH.EXT or ANYTHING and replaces it with EXT. If ANYTHING was matched, the ext group is not captured.

lang-bash
Morty Proxy This is a proxified and sanitized view of the page, visit original site.