P
P
plr2013-10-03 11:19:32
linux
plr, 2013-10-03 11:19:32

In script #!/bin/sh to variable value from execution (grep|awk|sed)

(I don't understand something)

In the script, I need to assign a value to a variable based on the result of executing (any tool) grep|awk|sed, i.e. design:

x=$(lsusb | grep ...)


So that not the entire “found” string appears in x, but only the numerical value of Bus.

Those. I use regular expressions to "find" the desired line, but as a result of grep (for example), I get the whole line, and I only need "001".

Let me remind you that the output of lsusb is:

# lsusb
Bus 001 Device 002: ID 12d1:1001 Huawei Technologies Co., Ltd. E169/E620/E800 HSDPA Modem
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

perl, python and other advanced tools BusyBox.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
G
Godless, 2013-10-03
@plr

grep has a parameter to output only a substring that matches the regular expression

egrep -o [...]
egrep --only-matching [...]

it will turn out something like
x=$(lsusb | egrep -o ...)

1
1x1, 2013-10-03
@1x1

| cut -f 2 -d ' '

M
mcleod095, 2013-10-03
@mcleod095

well, grep should output the line in which it found a match,
learn awk
x=$(lsusb | awk '/regexp/{print $2}')
for commands like
cat file | grep
beat yourself up,
you can also try
x=$(lsusb | grep regexp | cut -d" " -f 2)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question