Reputation: 2545
I know, that there is a way to get substring of a string variable:
MY_STR=abacaba
echo ${MY_STR:2:6}
Is there a way to get substring of a string given as literal constant? Something like:
echo ${"abacaba":2:6}
Upvotes: 4
Views: 859
Reputation: 616
expr
can deal with string literals.
expr substr STR POS LEN
So in your example, it should be expr substr 'abacaba' 3 6
Upvotes: 1
Reputation: 75488
There isn't but you could have alternatives like using a function:
function getsub {
sub="${1:$2:$3}"
}
getsub abacaba 2 6
echo "$sub"
function printsub {
echo "${1:$2:$3}"
}
printsub abacaba 2 6
Upvotes: 1
Reputation: 2543
If you don't mind using cut you could do:
echo "abacaba" | cut -c3-7
Upvotes: 1
Reputation: 123508
You can use cut
:
$ echo abacaba | cut -c3-7
acaba
Saying -c3-7
would get characters 3 to 7 (note that the first character is denoted by 1
).
For getting all the characters starting from the 3rd one, you could say:
$ echo abacaba | cut -c3-
acaba
You can also use tail
:
$ echo abacaba | tail -c+3
acaba
Upvotes: 3