我有一个正在运行的脚本并使用
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.
答案 0 :(得分:76)
使用tail
开关-c
怎么样?例如,要获取“hello”的最后4个字符:
echo "hello" | tail -c 5
ello
请注意,我使用了5(4 + 1),因为echo
添加了换行符。正如下面的Brad Koch所建议的那样,使用echo -n
来防止添加换行符。
答案 1 :(得分:16)
你真的想要最后四个角色吗?看起来你想要最后一行“单词”:
awk '{ print $NF }'
如果ID为3个字符或5,这将有效。
答案 2 :(得分:6)
使用sed
:
lspci -s 0a.00.1 | sed 's/^.*\(.\{4\}\)$/\1/'
输出:
4dc9
答案 3 :(得分:6)
试试这个,比如字符串是否存储在变量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
答案 4 :(得分:3)
我通常使用
echo 0a.00.1 usb controller some text device 4dc9 | rev | cut -b1-4 | rev
4dc9
答案 5 :(得分:3)
如果真实请求是复制最后一个以空格分隔的字符串,无论其长度如何,那么最佳解决方案似乎是使用@Johnsyweb给出的... | awk '{print $NF}'
。但是,如果这确实是从字符串末尾复制固定数量的字符,那么就有一个特定于bash的解决方案,而不需要通过管道来调用任何进一步的子进程:
$ test="1234567890"; echo "${test: -4}"
7890
$
请注意,冒号和减号之间的空格是必不可少的,因为没有它,将传递完整的字符串:
$ test="1234567890"; echo "${test:-4}"
1234567890
$
答案 6 :(得分:2)
尝试使用grep
:
lspci -s 0a.00.1 | grep -o ....$
这将打印每行的最后4个字符。
但是,如果您想要输出整个输出的最后4个字符,请改用tail -c4
。
答案 7 :(得分:0)
另一种方法是使用<<<
表示法:
tail -c 5 <<< '0a.00.1 usb controller some text device 4dc9'
答案 8 :(得分:0)
而不是使用命名变量,开发使用位置参数的做法,如下所示:
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.