LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Extracting nth length of character from a variable to another variable (https://www.linuxquestions.org/questions/linux-newbie-8/extracting-nth-length-of-character-from-a-variable-to-another-variable-878343/)

hayloiuy 05-02-2011 11:13 AM

Extracting nth length of character from a variable to another variable
 
Example, I want to extract the first four character from serial and store it into version.

Code:

serial= 10001100
version=...(codes)....
echo $version


output in the terminal:
1000

Just to show you guys i havent been lazy...

Code:

#!/bin/bash

serial=10110011
echo $serial> serial.txt

version= cut -c1-4  serial.txt

echo $version

but this code saves the value into a text file. I want a code that does not save into any file whatsoever. Help? Thanks.

Nylex 05-02-2011 11:17 AM

http://tldp.org/LDP/abs/html/string-manipulation.html.

cepheus11 05-02-2011 11:17 AM

The "cut" man page says: "With no FILE, or when FILE is -, read standard input."

Code:

version=$(echo $serial | cut -c1-4)
echo $version


Telengard 05-02-2011 12:01 PM

Quote:

Originally Posted by hayloiuy (Post 4343953)
Example, I want to extract the first four character from serial and store it into version.

Code:

serial=10001100
version=...(codes)....
echo $version


output in the terminal:
1000

Code:

foo$ serial=10001100
foo$ version=${serial:0:4}
foo$ echo $version
1000

http://www.gnu.org/software/bash/man...eter-Expansion

HTH

speedy64 05-02-2011 04:47 PM

I've had some success using typeset with ksh, does not work with bash.

Code:

typeset -L4 version

serial=10001100
version=$serial

echo $version



All times are GMT -5. The time now is 08:21 AM.