I'm trying to retrieve the first 5 characters from a string and but keep getting a Bad substitution
error for the string manipulation line, I have the following lines in my teststring.sh
script:
TESTSTRINGONE="MOTEST" NEWTESTSTRING=${TESTSTRINGONE:0:5} echo ${NEWTESTSTRING}
I have went over the syntax many times and cant see what im doing wrong
Thanks
To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction. length: The number of characters we need to extract from a string.
The substr syntax is: substr(string,starting position, offset). The string is the entire line which is $0. 0 is the starting position, 3 is the number of characters to extract.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
Depending on your shell, you may be able to use the following syntax:
expr substr $string $position $length
So for your example:
TESTSTRINGONE="MOTEST" echo `expr substr ${TESTSTRINGONE} 0 5`
Alternatively,
echo 'MOTEST' | cut -c1-5
or
echo 'MOTEST' | awk '{print substr($0,0,5)}'
echo 'mystring' |cut -c1-5
is an alternative solution to ur problem.
more on unix cut program
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With