How can I extract the last X chars from a string variable?
I'm reading the last line of a file into a variable. Then I want to get the last X characters of the string variable:
#!/bin/bash
someline="this is the last line content"
echo ${someline}
somepart=${someline: -5}
echo ${somepart}
Run with: sh lastchars.sh
Result:
this is the last line content
line 4: Bad substitution
What might be wrong here?
It sounds like you're not using bash
at all. I can only reproduce the error you show if I use dash
instead of bash
:
-
bash
:$ line="someline content" $ echo ${line} someline content $ lastchars=${line: -5} $ echo ${lastchars} ntent
-
dash
:$ line="someline content" echo ${line} lastchars=${line: -5} echo ${lastchars} $ someline content $ dash: 3: Bad substitution
Your shebang line is pointing to bash
, but you are running the script with sh
, so the shebang is ignored. /bin/sh
on Ubuntu systems is actually dash
, a minimal shell that doesn't support the syntax you are trying to use.
When using a shebang line, there's no reason to explicitly call a shell for the script, just make it executable (chmod a+x /path/to/script.sh
) and run it without specifying an interpreter:
/path/to/script.sh
Alternatively, just use the right one:
bash /path/to/script.sh
Obviously using the build-in functions of a certain shell are nice, but you can also accomplish the task using standard UNIX commands, so it will work in any shell:
String="This is some text"
StrLen=`echo ${String} | wc -c`
From=`expr $StrLen - 5`
echo $String | cut -c${From}-${StrLen}