Skip to content

Latest commit

 

History

History
42 lines (30 loc) · 1.42 KB

substring-extractions.md

File metadata and controls

42 lines (30 loc) · 1.42 KB

Bash substring extractions

(2021/07/27)

Bash allows for easy (and pretty powerful) substring extractions.


Syntax:

${<SOURCE_STRING><OPERATOR><MATCHING_PATTERN>}


MATCHING_PATTERN:

Follows the usual pattern matching techniques.

E.g. *ski matches "Bartek Lipinski".

OPERATOR:

  • # deletes the shortest match of MATCHING_PATTERN searching from the front of SOURCE_STRING.

    URL='https://www.youtube.com/watch?v=dQw4w9WgXcQ'
    SUBSTRING="${URL#*://}"
    # SUBSTRING is 'www.youtube.com/watch?v=dQw4w9WgXcQ'
    
    # removes the shortest string that matches `*://` from the front of $URL
  • ## deletes the longest match of MATCHING_PATTERN searching from the front of SOURCE_STRING.

    URL='https://www.youtube.com/watch?v=dQw4w9WgXcQ'
    SUBSTRING="${URL##*/w}"
    # SUBSTRING is 'atch?v=dQw4w9WgXcQ'
    
    # removes the longest string that matches `*/w` from the front of $URL
    # if it was using '# (the shortest) the SUBSTRING would be 'ww.youtube.com/watch?v=dQw4w9WgXcQ'
    # but for the '##' SUBSTRING is 'atch?v=dQw4w9WgXcQ' because it matches the last '/w'
  • % deletes the shortest match of MATCHING_PATTERN searching from the end of SOURCE_STRING.

  • %% deletes the longest match of MATCHING_PATTERN searching from the end of SOURCE_STRING.