Friday, May 27, 2022

[SOLVED] Convert a sed command into awk to work with variables

Issue

I have this file which contains:

cat file.txt
<interface type='network'>
      <mac address='FXP-MACADDRESS'/>
      <source network='FXP-BRIDGE'/>
      <target dev='FXP-INT-NAME'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>

By using this command:

cat file.txt | sed -n '1,/0x03/p' | tail -6 | awk '/mac address/ {print $2}' | awk -F"'" '{print $2}'

Output:
FXP-MACADDRESS

My problem is that I was reading that sed does not allow variables to be used. I would like to convert 0x03 into for example fxp0_slot=0x03 and use $fxp0_slot in the command.

Does anyone knows an alternative to obtain the same output but by using variables instead?


Solution

After digging around I was able to find the solution:

slot3=0x03

cat ... | awk '{a[++i]=$0;}''/'$slot3'/{for(j=NR-5;j<=NR;j++)print a[j];}'


Answered By - nickcrv06
Answer Checked By - Marie Seifert (WPSolving Admin)