BASH:从Standard Out,Inline获取输出的最后4个字符

我有一个正在运行和使用的脚本

lspci -s 0a.00.1 

这返回

 0a.00.1 usb controller some text device 4dc9 

我想要得到最后4个字符内联

 lspci -s 0a.00.1 | some command to give me the last 4 characters. 

tail怎么样,用-c开关。 例如,要获得“hello”的最后4个字符:

 echo "hello" | tail -c 5 ello 

请注意,我使用5(4 + 1),因为换行添加了换行符。 正如下面Brad Koch所建议的那样,使用echo -n来防止添加换行符。

你真的想要最后四个字吗? 它看起来像你想要的最后一个“单词”就行了:

 awk '{ print $NF }' 

如果ID是3个字符或5,这将工作。

使用sed

 lspci -s 0a.00.1 | sed 's/^.*\(.\{4\}\)$/\1/' 

输出:

 4dc9 

试试这个,如果字符串存储在变量foo中。

 foo=`lspci -s 0a.00.1` # the foo value should be "0a.00.1 usb controller some text device 4dc9" echo ${foo:(-4)} # which should output 4dc9 

我通常使用

 echo 0a.00.1 usb controller some text device 4dc9 | rev | cut -b1-4 | rev 4dc9 

尝试使用grep

 lspci -s 0a.00.1 | grep -o ....$ 

这将打印每行的最后4个字符。

但是,如果您想要输出整个输出的最后4个字符,请改用tail -c4

如果真正的请求是复制最后一个由空格分隔的字符串而不考虑它的长度,那么最好的解决方案似乎是使用... | awk '{print $NF}' ... | awk '{print $NF}'由@Johnsyweb给出。 但是,如果这确实是从字符串的末尾复制固定数量的字符,那么有一个特定于bash的解决方案,而不需要通过管道调用任何进一步的子进程:

 $ test="1234567890"; echo "${test: -4}" 7890 $ 

请注意,冒号和减号之间的空格是必不可少的,因为没有它,完整的字符串将被传送:

 $ test="1234567890"; echo "${test:-4}" 1234567890 $ 

还有一种方法是使用<<<符号:

 tail -c 5 <<< '0a.00.1 usb controller some text device 4dc9' 

而不是使用命名变量,开发使用位置参数的做法,如下所示:

 set -- $( lspci -s 0a.00.1 ); # then the bash string usage: echo ${1:(-4)} # has the advantage of allowing N PP's to be set, eg: set -- $(ls *.txt) echo $4 # prints the 4th txt file.