Home » Linux » BASH : Get the last 4 characters of output from Standard Out, Inline

BASH : Get the last 4 characters of output from Standard Out, Inline

Posted by: admin November 30, 2017 Leave a comment

Questions:

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. 
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.

Questions:
Answers:

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.

Questions:
Answers:

Using sed:

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

Output:

4dc9

Questions:
Answers:

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

Questions:
Answers:

I usually use

echo 0a.00.1 usb controller some text device 4dc9 | rev | cut -b1-4 | rev
4dc9

Questions:
Answers:

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.

Questions:
Answers:

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
$

Questions:
Answers:

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

tail -c 5 <<< '0a.00.1 usb controller some text device 4dc9'

Questions:
Answers:

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.