如何从linux中的字符串中提取以用户定义的特殊字符开头和结尾的子字符串?

时间:2020-12-08 19:16:31

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

我正在开发linux脚本,并希望从主字符串中提取一个子字符串,如下例所示:-

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.

该代码将在linux脚本中使用。

4 个解决方案

#1


0  

POSIX sh compatible:

POSIX sh兼容:

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

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

假定^是只用2 x / 2分隔符字符串。

#2


1  

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

#3


1  

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.

解决方案bellow使用cut实用程序,它生成一个进程,并且比shell参数展开解决方案要慢。它可能更容易理解,可以在文件上运行,而不是在单个字符串上。

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

#4


1  

You can also use bash arrays and field separator:

您还可以使用bash数组和字段分隔符:

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

#1


0  

POSIX sh compatible:

POSIX sh兼容:

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

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

假定^是只用2 x / 2分隔符字符串。

#2


1  

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

#3


1  

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.

解决方案bellow使用cut实用程序,它生成一个进程,并且比shell参数展开解决方案要慢。它可能更容易理解,可以在文件上运行,而不是在单个字符串上。

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

#4


1  

You can also use bash arrays and field separator:

您还可以使用bash数组和字段分隔符:

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