我想在 Shellscript 中提取两个字符串之间的文本。我想从下面的字符串中提取“Summary:”和“Arrived at”之间的文本。
mySTring="Summary: New Arrival Arrived At:11/8/2018, 01:38:00 P.M."
如何才能做到这一点?
答案1
严格遵循要求,假设文本已经在变量中,您将执行以下操作:
s="Summary: New Arrival Arrived At:11/8/2018, 01:38:00 P.M."
s="${s#*Summary:}"
s="${s%% Arrived At*}"
printf '%s\n' "$s"
...但是如果你的数据后面总是有一个空格Summary:
,那么你可能也想将其删除:
s="${s#*Summary: }"
s="${s%%Arrived At*}"
...与之前的前导空格同上Arrived At
:
s="${s#*Summary: }"
s="${s%% Arrived At*}"
答案2
使用 grep 和 Perl Regex 也可以实现同样的效果。
$ echo "$mySTring" | grep -Po "Summary: \K(.*)(?= Arrived )"
New Arrival
\K:grep 将保留 \K 之前的所有内容来匹配模式,但在打印时,它将被排除。
?= 是正向先行 捕获的部分后面必须跟有括号中的该部分才能捕获,但最终输出不会打印或提取。
答案3
$ mySTring="Summary: New Arrival Arrived At:11/8/2018, 01:38:00 P.M."
$ echo ${mySTring}
Summary: New Arrival Arrived At:11/8/2018, 01:38:00 P.M.
$ echo ${mySTring} | sed "s/.*Summary://;s/Arrived.*//"
New Arrival
如果你只想使用 bash 来做到这一点,那么试试这个..
mySTring="Summary: New Arrival Arrived At:11/8/2018, 01:38:00 P.M."
mySTring=${mySTring#*:}
$ echo ${mySTring}
New Arrival Arrived At:11/8/2018, 01:38:00 P.M.
$ echo ${mySTring%%Arrived*}
New Arrival
$ mySTring=${mySTring%%Arrived*}
$ echo ${mySTring}
New Arrival
bash 中的字符串操作 -https://www.tldp.org/LDP/abs/html/string-manipulation.html