从标准输出获取输出的最后 4 个字符
我有一个正在运行并使用
lspci -s 0a.00.1
This 返回的
0a.00.1 usb controller some text device 4dc9
脚本我想要内联最后 4 个字符,以便
lspci -s 0a.00.1 | some command to give me the last 4 characters.
I have a script that is running and uses
lspci -s 0a.00.1
This returns
0a.00.1 usb controller some text device 4dc9
I want to get those last 4 characters inline such that
lspci -s 0a.00.1 | some command to give me the last 4 characters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
使用
-c
开关的tail
怎么样。例如,要获取“hello”的最后 4 个字符:请注意,我使用了 5 (4+1),因为
echo
添加了换行符。正如下面 Brad Koch 所建议的,使用echo -n
来防止添加换行符。How about
tail
, with the-c
switch. For example, to get the last 4 characters of "hello":Note that I used 5 (4+1) because a newline character is added by
echo
. As suggested by Brad Koch below, useecho -n
to prevent the newline character from being added.你真的想要最后四个字符吗?看起来您想要该行的最后一个“单词”:
如果 ID 为 3 个字符或 5 个字符,这也将起作用。
Do you really want the last four characters? It looks like you want the last "word" on the line:
This will work if the ID is 3 characters, or 5, as well.
使用 sed:
输出:
Using
sed
:Output:
试试这个,假设字符串存储在变量 foo 中。
Try this, say if the string is stored in the variable foo.
我通常使用
I usually use
如果真正的请求是复制最后一个以空格分隔的字符串,无论其长度如何,那么最好的解决方案似乎是使用
... | awk '{print $NF}'
由@Johnsyweb 给出。但是,如果这确实是从字符串末尾复制固定数量的字符,那么有一个特定于 bash 的解决方案,无需通过管道调用任何进一步的子进程:请注意,冒号和减号字符之间的空格至关重要,如果没有它,将传递完整的字符串:
If the real request is to copy the last space-separated string regardless of its length, then the best solution seems to be using
... | awk '{print $NF}'
as given by @Johnsyweb. But if this is indeed about copying a fixed number of characters from the end of a string, then there is a bash-specific solution without the need to invoke any further subprocess by piping:Please note that the space between colon and minus character is essential, as without it the full string will be delivered:
尝试使用
grep
:这将打印每行的最后 4 个字符。
但是,如果您想要整个输出的最后 4 个字符,请改用
tail -c4
。Try using
grep
:This will print last 4 characters of every line.
However if you'd like to have last 4 characters of the whole output, use
tail -c4
instead.解决此问题的另一种方法是使用
<<<
表示法:One more way to approach this is to use
<<<
notation:不要使用命名变量,而是开发使用位置参数的实践,如下所示:
instead of using named variables, develop the practice of using the positional parameters, like this: