Skip to content

Instantly share code, notes, and snippets.

@terrisgit
Last active June 2, 2023 20:04
Show Gist options
  • Select an option

  • Save terrisgit/9356828fad9726e09ddc258b179c64d1 to your computer and use it in GitHub Desktop.

Select an option

Save terrisgit/9356828fad9726e09ddc258b179c64d1 to your computer and use it in GitHub Desktop.
sed: Find and Replace Regular Expression with Capture Groups Example
#! /bin/sh
# Complex string manipulation in Bash example
#
# Transforms a string in the form of: "archives/A/B C", to: A/B/B C
line='"A/B C",'
# Remove starting "
line="${line#\"}"
# Remove ending "
line="${line%\"}"
# Remove ending ,
line="${line%,}"
# Remove archives/ at the beginning
line="${line#archives/}"
# With sed, the following characters must be escaped: ( ) + /
line=`echo $line | sed -e 's/\([^\/]\+\)\/\([^ ]\+\)\(.*\)/\1\/\2\/\2\3/'`
# ^Group 1 ^ ^Group 2^ ^G3 ^
echo "$line"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment