Last active
June 2, 2023 20:04
-
-
Save terrisgit/9356828fad9726e09ddc258b179c64d1 to your computer and use it in GitHub Desktop.
sed: Find and Replace Regular Expression with Capture Groups Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /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