1

I have two regular expressions i.e. command1 and command2 where i need to combine both expressions into a single expression using | for that command1 output should be passed to next expression.

command1:

grep 0x017a /sys/bus/pci/devices/*/device | cut -d/ -f6
>> Output : 00:00:01

command 2:

head -n1 /sys/bus/pci/devices/00:00:01/resource | cut -d ' ' -f 1 | tail -c 9

How to use command1 output (00:00:01) into command2 and combine into a single expression?

  • Does head -n1 /sys/bus/pci/devices/`grep 0x017a /sys/bus/pci/devices/*/device | cut -d/ -f6`/resource | cut -d ' ' -f 1 | tail -c 9 work? – Hagen von Eitzen Feb 12 at 1:01
  • I have tried but didn't work this way. – Seshagiri Lekkala Feb 12 at 1:09
  • what does command 2 return, what is the desired output? – Evan Carroll Feb 12 at 1:59
  • "head -n1 /sys/bus/pci/devices/00:00:01/resource | cut -d ' ' -f 1 | tail -c 9 " output is : da00000. – Seshagiri Lekkala Feb 12 at 2:03
  • Here, 00:00:01 is command 1 output. – Seshagiri Lekkala Feb 12 at 2:04
1

To use the output of one command as argument of the second command the mechanism of command substitution $() can be utilized. For example:

Instead of

$ whoami
jimmij

$ ls /home/jimmij/tmp
file1 file2

you can do

$ ls /home/"$(whoami)"/tmp
file file2

In your specific case the single command become

head -n1 "/sys/bus/pci/devices/$(grep 0x017a /sys/bus/pci/devices/*/device | cut -d/ -f6)/resource" | cut -d ' ' -f 1 | tail -c 9

Notice I also quoted the entire expression, read here why you should do that.

1

Use the $(command) syntax (or the older `command` syntax).

DEVICE=$(grep 0x017a /sys/bus/pci/devices/*/device | cut -d/ -f6)
head -n1 "/sys/bus/pci/devices/$DEVICE/resource" | cut -d ' ' -f 1 | tail -c 9

Oh. "Combine into a single expression" similarly.

DEVICE=$(grep 0x017a /sys/bus/pci/devices/*/device | cut -d/ -f6)
OUTPUT=$(head -n1 "/sys/bus/pci/devices/$DEVICE/resource" | cut -d ' ' -f 1 | tail -c 9)

echo "Output is $OUTPUT"
  • May i know how can we combine both line into single line ? – Seshagiri Lekkala Feb 12 at 1:57
  • Get out of the habit of using ALLCAPS varnames: one day you'll use PATH=... and then wonder why your script is broken. – glenn jackman Feb 12 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.