[英]Bash get n characters before a specified character
This is the string: 这是字符串:
Volume: 0: 120% 1: 128%
I want to get 3 characters before "%" character. 我想在“%”字符之前得到3个字符。 So output must be like
120 128
for this example. 因此,对于此示例,输出必须类似于
120 128
。 How can i do that? 我怎样才能做到这一点?
假设您实际上想要空格和%之间的所有内容(此示例与此相同),则可以执行以下操作:
awk '{print $NF}' RS=% ORS=' '
You can use this grep
: 您可以使用以下
grep
:
$ grep -Po '...(?=%)' file
120
128
Which is the same as: 与以下内容相同:
grep -Po '.{3}(?=%)' file
or this if you want to make sure you get digits: 或者,如果您想确保获得数字,请执行以下操作:
grep -Po '[0-9]{3}(?=%)' file
The idea underlying is to print three characters before %
is found. 基本思想是在找到
%
之前先打印三个字符。 (?=%)
indicates this and is called a "look-ahead". (?=%)
表示这一点,称为“超前”。
With -Po
we indicate grep that it can use Perl regular expressions ( -P
) and to just print the matches ( -o
). 使用
-Po
表示grep它可以使用Perl正则表达式( -P
)并仅打印匹配项( -o
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.