Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to retrieve first 5 characters from string in bash error?

Tags:

bash

shell

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

like image 960
Mo. Avatar asked Jan 19 '12 15:01

Mo.


People also ask

How do I get the first character of a string in Bash?

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.

How do you get the first 3 characters of a string in Unix?

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.

What is $@ in Bash?

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.


2 Answers

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)}' 
like image 108
Alex L Avatar answered Sep 22 '22 02:09

Alex L


echo 'mystring' |cut -c1-5 is an alternative solution to ur problem.

more on unix cut program

like image 33
Balaswamy Vaddeman Avatar answered Sep 20 '22 02:09

Balaswamy Vaddeman