首页 > 解决方案 > 按照模式提取字符串(grep)

问题描述

我正在尝试学习如何使用 grep。我有一个文件列出了我的 python 包,如下所示:

channels:
  - conda-forge
  - defaults
dependencies:
  - numpy=1.21.1=py39h6635163_0
  - pyinstaller=4.2=py39h4dafc3f_1
  - ...

我只对“依赖”之后的内容感兴趣。我正在尝试使用 bash grep/sed/awk 任何基本的 linux 工具来迭代所有这些行,将 python 包保存在一个变量中,并将版本保存在另一个变量中(我不关心最后一个 = 之后的内容)和调用一个函数。

第一行的示例:

$ > echo $1 $2
numpy 1.21.1

谢谢你的帮助

标签: awksedgrep

解决方案


你可以使用这个:

grep -oP "\w+=[\d.]+" test.txt | while IFS="=" read -r P V; do
    export A=$P
    export B=$V
done

其中 test.txt 是:

channels:
  - conda-forge
  - defaults
dependencies:
  - numpy=1.21.1=py39h6635163_0
  - pyinstaller=4.2=py39h4dafc3f_1
  - ...

$A 是包名,$B 是版本


推荐阅读