bash 如何在shell中拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15409947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:51:30  来源:igfitidea点击:

How to split a string in shell

regexstringbashshell

提问by XYZ_Linux

I have a variable as

我有一个变量

string="ABC400p2q4".

how can I separate ABC400and p2q4. I need to separate it in two variables in such a way that as a result I get

我怎么能分开ABC400p2q4。我需要将它分成两个变量,结果我得到

echo $var1
ABC400
echo $var2
p2q4

In place of ABC there can be any alphabetic characters; in place of 400 there can be any other digits; but pand qare fixed and in place of 2 and 4 as well there can be any digit.

代替 ABC 可以有任何字母字符;可以有任何其他数字代替 400;但是pandq是固定的,可以代替 2 和 4 并且可以是任何数字。

回答by Chris Seymour

No need to split based on a regexp pattern as they are fixed length substrings. In pure bashyou would do:

无需根据正则表达式模式进行拆分,因为它们是固定长度的子字符串。纯粹bash你会这样做:

$ string="ABC400p2q4"

$ var1=${string:0:6}

$ var2=${string:6}

$ echo $var1
ABC400

$ echo $var2
p2q4

回答by Gilles Quenot

Using bashand special BASH_REMATCHarray (non fixed length) :

使用bash和特殊BASH_REMATCH数组(非固定长度):

$ string='ABC400p2q4'
$ [[ $string =~ ^([a-zA-Z]+[0-9]+)(.*) ]]
$ echo ${BASH_REMATCH[1]}
ABC400
$ echo ${BASH_REMATCH[2]}
p2q4

回答by Gilles Quenot

Try doing this

尝试这样做

using bash& process substitution(non fixed length) :

使用bash进程替换(非固定长度):

read var1 var2 < <(sed -r 's/^[a-zA-Z]+[0-9]+/& /' <<< 'ABC400p2q4')

or this using a here-string

或使用此处的字符串

read var1 var2 <<< $(sed -r 's/^[a-zA-Z]+[0-9]+/& /' <<< 'ABC400p2q4')

or with the short sed substitutionversion from Kent

sed substitution来自肯特的简短版本

's/([0-9])p/ p/'

Note

笔记

&in the sedcommand stands for the matching left part of the substitutions///

&sed命令中代表替换的匹配左侧部分s///

Output

输出

$ echo $var1
ABC400
$ echo $var2
p2q4

回答by Spencer Rathbun

The answer provided by sudo_O is perfect if your strings stay single length. But, if that isn't the case, bash does provide you with string regex matching builtins.

如果您的字符串保持单一长度,则 sudo_O 提供的答案是完美的。但是,如果情况并非如此,bash 确实为您提供了字符串正则表达式匹配 builtins

$ string="ABC400p2q4"

$ var1=$( expr match "$string" '\(.{6}\)' )

$ var2=$( expr match "$string" '.*\(.{4}\)' )

Replace the regex with whatever you actually need.

用您实际需要的任何内容替换正则表达式。