在 BASH 中截断输出

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

truncate output in BASH

linuxbash

提问by Amir Arad

How do I truncate output in BASH?

如何在 BASH 中截断输出?

For example, if I "du file.name" how do I just get the numeric value and nothing more?

例如,如果我“du file.name”,我如何只获取数值而仅此而已?

later addition:
all solutions work perfectly. I chose to accept the most enlightning "cut" answer because I prefer the simplest approach in bash files others are supposed to be able to read.

后来补充:
所有解决方案都完美无缺。我选择接受最有启发性的“剪切”答案,因为我更喜欢其他人应该能够阅读的 bash 文件中的最简单方法。

回答by Ken

If you know what the delimiters are then cut is your friend

如果你知道分隔符是什么,那么 cut 就是你的朋友

du | cut -f1

Cut defaults to tab delimiters so in this case you are selecting the first field.

剪切默认为制表符分隔符,因此在这种情况下您选择的是第一个字段。

You can change delimiters: cut -d ' ' would use a space as a delimiter. (from Tomalak)

您可以更改分隔符: cut -d ' ' 将使用空格作为分隔符。(来自托马拉克

You can also select individual character positions or ranges:

您还可以选择单个字符位置或范围:

ls | cut -c1-2

回答by Mark Baker

I'd recommend cut, as others have said. But another alternative that is sometimes useful because it allows any whitespace as separators, is to use awk:

正如其他人所说,我建议削减。但是另一种有时有用的替代方法是使用 awk,因为它允许任何空格作为分隔符:

du file.name | awk '{print }'

回答by Tomalak

du | cut -f 1

回答by Andy Lester

If you just want the number of bytes of a single file, use the -soperator.

如果您只想要单个文件的字节数,请使用-s运算符。

SIZE=-s file.name

That gives you a different number than du, but I'm not sure how exactly you're using this.

这为您提供了与 不同的数字du,但我不确定您究竟是如何使用它的。

This has the advantage of not having to run du, and having bashget the size of the file directly.

这样做的好处是不必运行du,并且bash可以直接获取文件的大小。

It's hard to answer questions like this in a vacuum, because we don't know how you're going to use the data. Knowing that might suggest an entirely different answer.

很难在真空中回答这样的问题,因为我们不知道您将如何使用这些数据。知道这可能会暗示一个完全不同的答案。