Removing Substring In Bash With Parameter Expansion

Pavol Kutaj
1 min readDec 14, 2021

The aim of this page📝is to see how a part of the string can be removed using the parameter expansion feature of bash.

  • parameter expansion allows quite powerful string manipulation in bash
  • e.g. the length of a variable is obtained via
${#<var>}
  • there are 3 elements to parameter expansion syntax
  • ${} const wrapper
  • <var> variable name
  • #,... special character defining the type of expansion

1. syntax

SYNTAX              | LENGTH   | FROM
--------------------|----------|--------------
${<var>#<pattern>} | shortest | the beginning
${<var>##<pattern>} | longest | the beginning
${<var>%<pattern>} | shortest | the end
${<var>%%<pattern>} | longest | the end
  • <patterns> are globbing patterns using
  • * match any string
  • ? match single char
  • [] match set of chars

2. example

i="/users/pkutaj/demo.txt"

<!-- SHORTEST FROM THE BEGINNING -->
>>> echo ${i#*/}
users/pkutaj/demo.txt

<!-- LONGEST FROM THE BEGINNING-->
>>> echo ${i##*/}
demo.txt

<!-- SHORTEST FROM THE END -->
>>> echo ${i%/*}
/users/pkutaj

<!-- LONGEST FROM THE END -->
>>> echo ${i%/*}

🠉 all is removed

3. links

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com