简体   繁体   English

如何在 bash 中的某些字符之间获取 2 个字符串

[英]How to get 2 strings between certain characters in bash

String:细绳:

echo "40125512|abcd32External_SOC=ALPHA3;PCRFabcran"

I want to grab everything before the first instance of |我想在 | 的第一个实例之前抓住一切and everything between External_SOC and;PCRF.以及 External_SOC 和;PCRF 之间的所有内容。 And store them as 2 different variables if possible.如果可能,将它们存储为 2 个不同的变量。

x=40125512
y=ALPHA3

This gives me the following:这给了我以下信息:

sed -e 's/|.*External_SOC=\(.*\);PCRF.*/\1/'

40125512ALPHA3 40125512ALPHA3

EDIT: As per OP it needs to be done in a single line creation 2 of variables if this is the case then try following.编辑:根据 OP,如果是这种情况,则需要在单行创建变量 2 中完成,然后尝试以下操作。

read -r x y <<<$(echo "40125512|abcd32External_SOC=ALPHA3;PCRFabcran" | sed 's/\([^|]*\).*=\([^;]*\).*/\1 \2/')
echo "$x"
40125512
echo "$y"
ALPHA3

OR use following as per anubhav sir's comment:或根据 anubhav 先生的评论使用以下内容:

read x y < <(sed -E 's~^([^|]+)\|.*External_SOC=(.+);PCRF.*~\1 \2~' <<< "40125512|abcd32External_SOC=ALPHA3;PCRFabcran")


Could you please try following.请您尝试以下操作。 One could use it from 2 separate commands to create 2 separate variables.可以从 2 个单独的命令中使用它来创建 2 个单独的变量。

x=$(echo "40125512|abcd32External_SOC=ALPHA3;PCRFabcran" | sed 's/\([^|]*\).*/\1/')
echo "$x"
40125512

y=$(echo "40125512|abcd32External_SOC=ALPHA3;PCRFabcran" | sed 's/.*=\([^;]*\).*/\1/')
echo "$y"
ALPHA3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM