bash:strings:get_a_substring
This is an old revision of the document!
BASH - Get a SubString
To cut portions of a string:
#!/bin/bash Str="My name is Peter" subStr=${Str:0:6} echo $subStr
This script should print out “My nam” as its output.
The parameter expansion takes the form ${VAR_NAME:S:L}.
Here, S denotes starting position and L indicates the length.
Extracting Substrings Using Cut
cut can be used to ‘cut’ a portion of a string, aka the substring.
#!/bin/bash Str="My name is Peter" #subStr=${Str:0:6} subStr=$(echo $Str| cut -d ' ' -f 1-3) echo $subStr
In general to concatenate two variables you can just write them one after another:
a='Hello' b='World' c="${a} ${b}" echo "${c}" > Hello World
or
foo="Hello" foo="${foo} World" echo "${foo}" > Hello World
bash/strings/get_a_substring.1610575604.txt.gz · Last modified: 2021/01/13 22:06 by peter