【问题标题】:How to split string according to regex in bash script如何根据bash脚本中的正则表达式拆分字符串
【发布时间】:2017-12-14 23:35:39
【问题描述】:

我有这样一个字符串:

msg='123abc456def'

现在我需要拆分msg并得到如下结果:

['123', 'abc', '456', 'def']

在 python 中,我可以这样做:

pattern = re.compile(r'(\d+)')
res = pattern.split(msg)[1:]

如何在 bash 脚本中获得相同的结果?
我试过这样但它不起作用:

IFS='[0-9]'    # how to define IFS with regex?
echo ${msg[@]}

【问题讨论】:

  • 为什么不直接调用你的 Python 脚本呢?

标签: python regex bash split


【解决方案1】:

鉴于您已经知道如何在 Python 中解决这个问题,您可以使用问题中显示的代码来解决它:

MSG=123abc456def;
python -c "import re; print('\n'.join(re.split(r'(\\d+)', '${MSG}')[1:]))"

虽然python 不像grepawk 那样作为可执行文件的标准,但这对你来说真的很重要吗?

【讨论】:

  • 谢谢!当我有来自 bash 管道的字符串列表(每个都在换行符中)时,我可以在 bash 脚本中使用它吗?
  • @Nikhil。请提出一个新的具体问题。如果你想让我看一下,请随时联系我。
【解决方案2】:

使用grep 获取子字符串,并使用命令替换将输出放入数组中:

$ msg='123abc456def'

$ out=( $(grep -Eo '[[:digit:]]+|[^[:digit:]]+' <<<"$msg") )

$ echo "${out[0]}"
123

$ echo "${out[1]}"
abc

$ echo "${out[@]}"
123 abc 456 def
  • 正则表达式 (ERE) 模式 [[:digit:]]+|[^[:digit:]]+ 匹配一个或多个数字 ([[:digit:]]+) 或 (|) 一个或多个非数字 ([^[:digit:]]+

【讨论】:

    【解决方案3】:

    我会进行匹配而不是拆分。在这里,我使用了grep,但您也可以在纯 bash 中使用相同的正则表达式。

    $ msg='123abc456def'
    $ grep -oE '[0-9]+|[^0-9]+' <<<$msg
    123
    abc
    456
    def
    

    【讨论】:

      猜你喜欢
      • 2014-05-31
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多