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?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

2 Answers2

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

jimmij
  • 47,140