4

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}
2
  • How would that be useful (I remember I wanted to be able to do this before as well, but I really don't remember the use case)? Commented Sep 18, 2013 at 6:17
  • @AdrianFrühwirth, for using in inline commands. find . -exec bash -c "echo \"{}\" | cut -c3-" \; for example. Commented Sep 18, 2013 at 6:39

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

echo "abacaba" | cut -c3-7

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.