Created
August 24, 2019 07:42
-
-
Save mezorian/9bc43839b45eb51395c24072ee4d67e3 to your computer and use it in GitHub Desktop.
Extract a string between two strings with bash
This file contains 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/bash | |
strindex() { | |
x="${1%%$2*}" | |
[[ "$x" = "$1" ]] && echo -1 || echo "${#x}" | |
} | |
function extractStringBetweenStrings() { | |
# get parameters | |
string="$1" | |
stringBefore="$2" | |
stringAfter="$3" | |
# get lengths | |
lengthOfStringBefore=${#stringBefore} | |
lengthOfString=${#string} | |
# get positions | |
positionOfStringBefore=$( strindex "${string}" "${stringBefore}" ) | |
positionOfStringAfter=$( strindex "${string}" "${stringAfter}" ) | |
# cut from the end of stringBefore to the beginning of stringAfter | |
cutPositionStart=$((${positionOfStringBefore} + ${lengthOfStringBefore} + 1)) | |
cutPositionEnd=${positionOfStringAfter} | |
extractedString=$(echo ${string} | cut -c ${cutPositionStart}-${cutPositionEnd}) | |
# output extracted string | |
echo "${extractedString}" | |
} | |
wholeStrings='<Test XML name="Test1234" revision="master" />' | |
extractStringBetweenStrings "${wholeStrings}" '<Test XML name="' '" revision="' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment