Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last 4 characters of output from standard out

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.  
like image 863
bing281 Avatar asked Feb 09 '12 22:02

bing281


People also ask

How do I get the last 4 characters of a string in bash?

Getting the last n characters To access the last n characters of a string, we can use the parameter expansion syntax ${string: -n} in the Bash shell. -n is the number of characters we need to extract from the end of a string.

How do I get the last 3 characters of a string in Unix?

This solution instead uses the substring function of awk to select a substring which has the syntax substr(string, start, length) going to the end if the length is omitted. length($string)-2) thus picks up the last three characters.

How do I get the last character in Linux?

To access the last character of a string, we can use the parameter expansion syntax ${string: -1} in the Bash shell. In bash the negative indices count from the end of a string, so -1 is the index of a last character.


1 Answers

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.

like image 148
Diego Avatar answered Sep 30 '22 03:09

Diego