A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

Showing posts with label pattern matching. Show all posts
Showing posts with label pattern matching. Show all posts

Bash parameter expansion

Have you ever seen ## (hash hash/pound pound) or %% (percent percent) inside a bash script and wondered what it means? It's a form of parameter expansion that allows you to manipulate your strings using regexes.

All the following commands work with a variable called $string.
'pattern' means bash pattern, or can also be an ordinary string:

  • String length: ${#string}
  • Extract a substring: ${string:position}
  • Extract a substring, specifying length: ${string:position:length}
  • Delete shortest match of substring from the beginning of string: ${string#substring}
  • Delete shortest match of substring from the end of string: ${string%substring}
  • Delete longest match of substring from the beginning of string: ${string##substring}
  • Delete longest match of substring from the end of string: ${string%%substring}
  • Find and replace first substring: ${string/pattern/replacement}
  • Find and replace all substrings: ${string//pattern/replacement}

Thanks to TheGeekStuff