Skip to content

Instantly share code, notes, and snippets.

@mflorida
Forked from Error601/pattern-matching.sh
Last active October 6, 2022 17:07
Show Gist options
  • Save mflorida/36bed7f4f5ee329a3b079c0903f8e30d to your computer and use it in GitHub Desktop.
Save mflorida/36bed7f4f5ee329a3b079c0903f8e30d to your computer and use it in GitHub Desktop.
Bash string removal pattern matching samples
#!/bin/bash
# file path example
FILE=/home/user/src.dir/prog.c
echo ${FILE#/*/} # ==> user/src.dir/prog.c -- remove everything BEFORE the SECOND '/'
echo ${FILE##*/} # ==> prog.c -- remove part BEFORE LAST '/'
echo ${FILE%/*} # ==> /home/user/src.dir -- remove everything AFTER the LAST '/'
echo ${FILE%%/*} # ==> nil -- remove everything AFTER the FIRST '/' (returns empty string)
echo ${FILE%.c} # ==> /home/user/src.dir/prog -- remove everything AFTER '.c'
# get file path or base name
echo ${FILE##*.} # ==> c -- extension -- remove part BEFORE LAST '.'
echo ${FILE%.*} # ==> /home/user/src.dir/prog -- base -- remove everything AFTER the LAST '.'
# string example
STR="one:two.3:four:five.6"
echo ${STR#*:} # ==> two.3:four:five.6 -- remove everything BEFORE the FIRST ':'
echo ${STR#*:*:} # ==> four:five.6 -- remove part BEFORE the SECOND ':'
echo ${STR##*:} # ==> five.6 -- remove part BEFORE the LAST ':'
echo ${STR%:*} # ==> one:two.3:four -- remove everything AFTER the LAST ':'
echo ${STR%.*} # ==> one:two.3:four:five -- remove everything AFTER the LAST '.'
echo ${STR%%:*} # ==> one -- remove everything AFTER the FIRST ':'
echo ${STR%.3*} # ==> one:two -- remove everything AFTER and including '.3'
# All this from the excellent book: "A Practical Guide to Linux Commands, Editors, and
# Shell Programming by Mark G. Sobell (http://www.sobell.com/)
# found here: http://stackoverflow.com/questions/1199613/extract-filename-and-path-from-url-in-bash-script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment