我有一臺運行,並使用BASH:獲取最後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.
我有一臺運行,並使用BASH:獲取最後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
開關。例如,爲了得到最後的4個字符的「你好」:
echo "hello" | tail -c 5
ello
注意,我使用的5(4 + 1),因爲一個換行符通過echo
加入。正如下面Brad Koch所建議的那樣,使用echo -n
來防止添加換行符。
我通常使用
echo 0a.00.1 usb controller some text device 4dc9 | rev | cut -b1-4 | rev
4dc9
儘管有效,但似乎很多流程都涉及到這項工作。 – 2012-02-14 15:24:32
@JonathanLeffler:但是非常快。我經常發現「rev | cut | rev」是所有可能解決方案中最快的。 – choroba 2012-02-14 22:17:11
使用sed
:
lspci -s 0a.00.1 | sed 's/^.*\(.\{4\}\)$/\1/'
輸出:
4dc9
你可以通過:sed -n'$ s /.* \(.... \)$/\ 1/p''來改善它。這隻會打印輸出的最後一行,並且4個點比用'。\ {4 \}'表示法描述它的6個字符更簡單。 – 2012-02-14 15:23:27
還有一個方法是使用<<<
符號:
tail -c 5 <<< '0a.00.1 usb controller some text device 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
工作得很好。謝謝。 – deppfx 2015-04-21 21:46:50
如果真正的要求是,無論以複製其長度的最後一個空格分隔字符串,那麼最好的解決辦法似乎是使用... | awk '{print $NF}'
通過@Johnsyweb給出。但是,如果這確實是有關從字符串的結尾開始複製字符固定數量的,再有就是,而不需要通過管道來調用任何其它子特定慶典的解決方案:
$ test="1234567890"; echo "${test: -4}"
7890
$
請注意,空間冒號和減號之間是必不可少的,因爲沒有它的完整字符串將交付到位:
$ test="1234567890"; echo "${test:-4}"
1234567890
$
道歉,我只是注意到這個解決方案實際上與Mingjiang Shi的建議相同,只是省略了偏移量的括號。 – 2015-03-27 16:09:51
如果需要,您可以刪除此答案。 – user4098326 2015-03-27 16:12:16
嘗試使用grep
:
lspci -s 0a.00.1 | grep -o ....$
這將打印每行最後4個字符。
但是,如果您想要輸出整個輸出的最後4個字符,請改爲使用tail -c4
。
而不是使用命名的變量,開發使用位置參數,這樣的做法:
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.
完美非常感謝 – bing281 2012-02-09 22:54:19
一個簡單而優雅的解決方案。在互聯網的其他地方,當我搜索時,我得到了一個更復雜的解決方案。但是這個,我認爲是最簡單和最棒的。謝謝。 – 2013-01-31 19:23:49
'echo -n'會阻止添加新行字節。 – 2013-04-17 17:35:58