开发者

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 :-

Maste开发者_高级运维r 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.


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


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


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


POSIX sh compatible:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜