Equivalent of Substr in Unix

Hi,

I have a shell variable which has a value 123456:abcdeg. I want to extract the value which is present before ":". Is there any command in Unix through which I can achieve this. Please suggest.

Thanks,
Saurabh

What I would do is

(a) pipe it through sed to change the : to a space

VAR=123456:abcdeg
VAR2=`echo $VAR | sed y/:/\ /`

(b) use a function to get the first part

first()
{
   return $1
}

VAR3=`first $VAR2`

You didn't say which shell you were using, but generally this should work:

# VAR="abc:123"
# echo ${VAR##*:}
123
# echo ${VAR%%:*}
abc

If that doesn't work, there are plenty of methods for chopping up strings:

# echo $VAR | awk -F: '{print $1}'
abc
# echo $VAR | sed 's/:.*//'
abc

Hi.

As gus2000 noted, you can do this in some shells. In most systems, expr also has some limited string matching:

#!/usr/bin/env sh

# @(#) s1       Demonstrate string extraction from variable.

set -o nounset
echo

debug=":"
debug="echo"

## Use local command version for the commands in this demonstration.

echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version bash expr

echo

VAR="123456:abcdeg"
echo " Goal: extract text before : from \"$VAR\""

echo
echo " Old school with expr string matching:"
expr $VAR : "\(.*\):"

echo
echo " bash / ksh parameter expansions:"
echo ${VAR%%:*}
echo ${VAR//:*}

exit 0

Producing:

% ./s1

(Versions displayed with local utility "version")
GNU bash 2.05b.0
expr (GNU coreutils) 5.2.1

 Goal: extract text before : from "123456:abcdeg"

 Old school with expr string matching:
123456

 bash / ksh parameter expansions:
123456
123456

See man pages for details ... cheers, drl

there's also echoing and piping into cut -f1 (or 2) -d':'

Thanks a lot for your inputs.

Hi.

You can also (re)set the argument string-vector:

echo
echo " Setting the argument vector:"
oldIFS="$IFS"
IFS=":"
set -- $VAR
IFS="$oldIFS"
echo " First argument is \"$1\""

Producing:

 Setting the argument vector:
 First argument is "123456"

cheers, drl

Hi, porter.

You probably wrote "return $1" in the function, meaning rather to write "echo $1" ... cheers, drl