citxx
citxx

Reputation: 2545

Bash: substring of a constant string

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

Answers (4)

ebk
ebk

Reputation: 616

expr can deal with string literals.

expr substr STR POS LEN
  • STR: the constant string.
  • POS: the index of the first char of the substring (starting from 1).
  • LEN: the length of the substring.

So in your example, it should be expr substr 'abacaba' 3 6

Upvotes: 1

konsolebox
konsolebox

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

pitseeker
pitseeker

Reputation: 2543

If you don't mind using cut you could do:

echo "abacaba" | cut -c3-7

Upvotes: 1

devnull
devnull

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

Related Questions