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:41

Using sed:

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

Output:

4dc9
查看更多
The star\"
3楼-- · 2019-03-09 08:45

Try using grep:

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

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.

查看更多
倾城 Initia
4楼-- · 2019-03-09 08:46

I usually use

echo 0a.00.1 usb controller some text device 4dc9 | rev | cut -b1-4 | rev
4dc9
查看更多
贼婆χ
5楼-- · 2019-03-09 08:47

Do you really want the last four characters? It looks like you want the last "word" on the line:

awk '{ print $NF }'

This will work if the ID is 3 characters, or 5, as well.

查看更多
老娘就宠你
6楼-- · 2019-03-09 08:47

One more way to approach this is to use <<< notation:

tail -c 5 <<< '0a.00.1 usb controller some text device 4dc9'
查看更多
Evening l夕情丶
7楼-- · 2019-03-09 08:50

How about tail, with the -c switch. For example, to get the last 4 characters of "hello":

echo "hello" | tail -c 5
ello

Note that I used 5 (4+1) because a newline character is added by echo. As suggested by Brad Koch below, use echo -n to prevent the newline character from being added.

查看更多
登录 后发表回答