I have a number of strings that follow the format:
" 3:[numbers and text]"
The key features are that thee string begins with many spaces and the desired portion is surrounded by brackets, which repeats on a sec. I want to extract the numbers and text portion of the string which corresponds to "numbers and text", which change on each occurrence of the string. Additionally, the string is saved as a variable, called var. I have thought of two ways to do this, neither of which have worked.
method 1: For every occurrence of the string, the part I want begins at index 24 and ends at the second to last character, so my attempt to extract this portion is:
var_truncated=${var:24:-1}
method 2: remove everything before and after the brackets, unsure how to do this
CodePudding user response:
Method 2
$ var_truncated=${var/*[}
$ var_truncated=${var_truncated/]*}
$ echo "$var_truncated"
numbers and text
CodePudding user response:
Maybe you could use the built-in pattern matching support in Bash:
test.sh
# https://github.com/micromatch/posix-character-classes#posix-character-classes
declare -r pat='^[[:space:]]*([[:digit:]] ):\[([^]] )\]$'
declare -r str=' 3:[numbers and text]'
if [[ $str =~ $pat ]]; then
declare -p BASH_REMATCH
echo "number: '${BASH_REMATCH[1]}'"
echo "string: '${BASH_REMATCH[2]}'"
fi
$ ./test.sh
declare -a BASH_REMATCH=([0]=" 3:[numbers and text]" [1]="3" [2]="numbers and text")
number: '3'
string: 'numbers and text'