BASH : Get the last 4 characters of output from St

2019-03-09 08:08发布

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. 

9条回答
不美不萌又怎样
2楼-- · 2019-03-09 08:50

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:

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

Please note that the space between colon and minus character is essential, as without it the full string will be delivered:

$ test="1234567890"; echo "${test:-4}"
1234567890
$
查看更多
再贱就再见
3楼-- · 2019-03-09 08:51

instead of using named variables, develop the practice of using the positional parameters, like this:

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.  
查看更多
戒情不戒烟
4楼-- · 2019-03-09 08:59

Try this, say if the string is stored in the variable 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
查看更多
登录 后发表回答