Gianluca Ghettini
Gianluca Ghettini

Reputation: 11628

Searching for and echoing a portion of string in bash

What's the best way (in bash) to search in a string for a given pattern and echoing it without using awk? I'd like to use the standard command like grep, cat, cut, or sed.

Example:

I want to strip out the device addresses of all the USB controllers from the output of lspci command:

[artlab@localhost ~]$ lspci

00:00.0 Host bridge: Intel Corporation Core Processor DRAM Controller (rev 18)
00:1a.0 USB controller: Intel Corporation 5 Series/3400 Series Chipset USB2 Enhanced Host Controller (rev 05)
00:1c.0 PCI bridge: Intel Corporation 5 Series/3400 Series Chipset PCI Express Root Port 1 (rev 05)
00:1c.4 PCI bridge: Intel Corporation 5 Series/3400 Series Chipset PCI Express Root Port 5 (rev 05)
00:1c.5 PCI bridge: Intel Corporation 5 Series/3400 Series Chipset PCI Express Root Port 6 (rev 05)
00:1d.0 USB controller: Intel Corporation 5 Series/3400 Series Chipset USB2 Enhanced Host Controller (rev 05)
00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev a5)
00:1f.0 ISA bridge: Intel Corporation 3400 Series Chipset LPC Interface Controller (rev 05)
00:1f.2 RAID bus controller: Intel Corporation 82801 SATA Controller [RAID mode] (rev 05)
00:1f.3 SMBus: Intel Corporation 5 Series/3400 Series Chipset SMBus Controller (rev 05)
02:00.0 Ethernet controller: Intel Corporation 82574L Gigabit Network Connection
03:00.0 Ethernet controller: Intel Corporation 82574L Gigabit Network Connection
04:03.0 VGA compatible controller: Matrox Graphics, Inc. MGA G200eW WPCM450 (rev 0a)

I'd like to retrieve (print out) the two strings:

00:1a.0
00:1d.0

Upvotes: 2

Views: 195

Answers (3)

miono
miono

Reputation: 344

lspci | grep 'USB Controller' | cut -d' ' -f1

Upvotes: 1

Guru
Guru

Reputation: 16974

sed -n '/USB controller/{s/ .*//;p}'

Upvotes: 1

January
January

Reputation: 17090

I wonder who will come up with more possibilities.

lspci | grep 'USB Controller' | sed "s/ .*//"
lspci | grep 'USB Controller' | grep -o '^[^ ]*'
lspci | grep 'USB Controller' | while read id rest ; do echo $id ; done
lspci | grep 'USB Controller' | cut -f 1 -d ' '

Upvotes: 3

Related Questions