简体   繁体   English

如何从文件中的某些文本中查找子字符串并将其存储在 bash 变量中?

[英]How to find a substring from some text in a file and store it in a bash variable?

I have a file named config.txt which has following data:我有一个名为 config.txt 的文件,其中包含以下数据:

ABC_PATH=xxx/xxx
IMAGE=docker.name.net:3000/apache:1.8.109.1
NAMESPACE=xxx

Now I am running a shell script in which I want to store 1.8.109.1 (this value may differ, rest will remain same) in a variable, maybe using sed, awk or any other linux tool.现在我正在运行一个 shell 脚本,我想在一个变量中存储 1.8.109.1(这个值可能不同,其余的将保持不变),可能使用 sed、awk 或任何其他 linux 工具。 How can I achieve that?我怎样才能做到这一点?

The following will work.以下将起作用。

ver="$(cat config.txt | grep apache: | cut -d: -f3)"

grep apache: will find the line that has the text 'apache:' in it. grep apache:将找到其中包含文本 'apache:' 的行。

-d specifies what delimiters to use. -d指定要使用的分隔符。 In this case : is set as the delimiter.在这种情况下 : 被设置为分隔符。 -f is used to select the specific field (array index, starting at 1) of the resulting list obtained after delimiting by : -f用于选择分隔后得到的结果列表的特定字段(数组索引,从 1 开始):

Thus, -f3 selects the 3rd occurence of the delimited list.因此,-f3 选择分隔列表的第 3 次出现。

The version info is now captured in the variable $ver版本信息现在被捕获在变量 $ver 中

我认为这应该有效:

cat config.txt | grep apache: | cut -d: -f3

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

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