Bash:如何在使用 cut 之前修剪空白
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38792983/
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
Bash: How to trim whitespace before using cut
提问by user2824889
I have a line of output from a command like this:
我有这样一行命令的输出:
[]$ <command> | grep "Memory Limit"
Memory Limit: 12345 KB
I'm trying to pull out the 12345. The first step - separating by the colon - works fine
我正在尝试拔出 12345。第一步 - 用冒号分隔 - 工作正常
[]$ <command> | grep "Memory Limit" | cut -d ':' -f2
12345 KB
Trying to separate this is what's tricky. How can I trim the whitespace so that cut -d ' ' -f1
returns "12345" rather than a blank?
试图将其分开是很棘手的。如何修剪空格以便cut -d ' ' -f1
返回“12345”而不是空白?
采纳答案by John Goofy
Pipe your command to awk, print the 3rd column, a space and the 4th column like this
将您的命令传送到 awk,像这样打印第 3 列、一个空格和第 4 列
<command> | awk '{print , }'
This results in:
这导致:
12345 KB
or
或者
<command> | awk '{print }'
if you want the naked number.
如果你想要裸号。
回答by anatoly techtonik
回答by anubhava
You can use awk
and avoid using any cut, sed or regex:
您可以使用awk
并避免使用任何 cut、sed 或 regex:
<command> | awk '/Memory Limit/{print $(NF-1)}'
12345
/Memory Limit/
will make this print only a line withMemory Limit
text$(NF-1)
will get youlast-1
th field in input.
/Memory Limit/
将使此打印仅带有Memory Limit
文本的一行$(NF-1)
将让您last-1
输入第 th 字段。
回答by Jason Hu
do you have to use cut
? cut
is only for single character delimiter extraction. i don't think cut can be as easy as you would expect.
你必须使用cut
吗?cut
仅用于单字符分隔符提取。我不认为切割会像你想象的那么容易。
sed
is straightforward:
sed
很简单:
$ echo "Memory Limit: 12345 KB" | sed 's/.*:\s*//'
12345 KB
explanation:
解释:
.*:\s*
matches all letters before the last colon, then matches all the empty chars after that and delete them by substituting to an empty string.
.*:\s*
匹配最后一个冒号之前的所有字母,然后匹配之后的所有空字符并通过替换为空字符串来删除它们。
it turns out that you were expecting a single number. then i would say just go ahead and match the numbers:
事实证明,您期待的是一个数字。然后我会说继续匹配数字:
$ echo "Memory Limit: 12345 KB" | grep -o -P '\d+'
12345
回答by chepner
bash
also has regular expression matching you can use.
bash
还可以使用正则表达式匹配。
result=$(<command> | grep "Memory Limit")
regex='Memory Limit:[[:space:]]+([[:digit:]]+)[[:space:]]KB'
if [[ $result =~ $regex ]]; then
result=${BASH_REMATCH[0]}
else
# deal with an unexpected result here
fi
The value of $regex
can be adjusted as necessary.
的值$regex
可以根据需要进行调整。
回答by karakfa
awk
is perhaps the best for this task, but here is an unorthodox way
awk
可能是这项任务的最佳选择,但这是一种非正统的方式
$ grep -oP "(?<=Memory Limit:)\s+[0-9]+" file | xargs
lookbehind for matching the label and output only matching, use xargs to eat up spaces
lookbehind 匹配标签,只输出匹配,使用 xargs 占用空间