SP Sandhu
SP Sandhu

Reputation: 2818

How to extract a substring beginning and ending with user defined special characters from a string in linux?

I am working on linux scripts and want to extract a substring out of a master string as in the following example :-

Master string =

2011-12-03 11:04:22#Alex#Audrino^13b11254^Townville#USA#    

What I require is :-

Substring =

13b11254    

I simply want to read and extract whatever is there in between ^ ^ special characters.

This code will be used in a linux script.

Upvotes: 2

Views: 2775

Answers (4)

jfg956
jfg956

Reputation: 16748

You can also use bash arrays and field separator:

IFS="^"
s='2011-12-03 11:04:22#Alex#Audrino^13b11254^Townville#USA#'
array=($s)
echo ${array[1]}

This allows you to test is you have exactly 2 separators:

if [ ${#array[*]} -ne 3 ]
then
  echo error
else
  echo ok
fi

Upvotes: 1

jfg956
jfg956

Reputation: 16748

The solution bellow uses the cut utility, which spawns a process and is slower that the shell parameter expansion solution. It might be easier to understand, and can be run on a file instead of on a single string.

s='2011-12-03 11:04:22#Alex#Audrino^13b11254^Townville#USA#'
echo $s | cut -d '^' -f 2

Upvotes: 1

Dimitre Radoulov
Dimitre Radoulov

Reputation: 28000

Using standard shell parameter expansion:

% s='2011-12-03 11:04:22#Alex#Audrino^13b11254^Townville#USA#' ss=${s#*^} ss=${ss%^*}
% printf '%s\n' "$ss"                                                                  
13b11254

Upvotes: 1

jw013
jw013

Reputation: 1808

POSIX sh compatible:

temp="${string#*^}"
printf "%s\n" "${temp%^*}"

Assumes that ^ is only used 2x per string as the 2 delimiters.

Upvotes: 1

Related Questions