Bash 字符串爆炸

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8943132/
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 01:22:57  来源:igfitidea点击:

Bash string explode

bashunixfreebsdexplode

提问by Cyclone

My file looks like this:

我的文件看起来像这样:

record=123
date=2012.01.20 10:22

In the bash file I do cat myfile.ini, and then I need to use something like explode, because I need ONLY to grep the 123numeric record data, and nothing else.

在我做的 bash 文件中cat myfile.ini,然后我需要使用诸如 expand 之类的东西,因为我只需要 grep123数字记录数据,而不需要其他任何东西。

How it can be done in the bash ?

如何在 bash 中完成?

回答by Paused until further notice.

awk -F'=| ' '/record/ {print }'

Substitute "date" for "record" in the command above to get the date (the time would be in $3).

将上面命令中的“记录”替换为“日期”以获取日期(时间将在$3)。

This keys on the names of the variables rather than depending on a regex match of the value. It uses spaces or equal signs as field separators.

这取决于变量的名称,而不是取决于值的正则表达式匹配。它使用空格或等号作为字段分隔符。

回答by mvds

If you have control over the ini file, rewrite it as:

如果您可以控制 ini 文件,请将其重写为:

record=123
date="2012.01.20 10:22"

Then in your "bash file" you do

然后在你的“bash文件”中你做

. myfile.ini

echo $record

This is the typical approach. (if you have control over the ini file)

这是典型的方法。(如果您可以控制 ini 文件

回答by xpapad

You can use:

您可以使用:

#!/bin/sh
VALUE="`grep '^record=' myfile.ini |sed 's/[^0-9]//g'`"

回答by anubhava

You can do something like this:

你可以这样做:

awk '/=[0-9]+$/' file.txt

to print only the line with numeric content after = signon stdout.

与后等号(=)数字内容只打印线的标准输出。

However if you just want to capture 123 into a variablethen you can use:

但是,如果您只想将123 捕获到变量中,则可以使用:

val=$(awk -F"=" '/=[0-9]+$/{print }' file.txt)