0

I need to parse the below command to extract namespace & interface names using a bash script. I generally do this using IFS, but that seems tedious to me. Is there a better way of doing this without setting IFS ?

    ovsdb-client dump Open_vSwitch  | grep nw-uplink    
    ffff-fff-ffff-ffff-fffffffff [ffff-fff-ffff-ffff-fffffffff] 10      "v1.1"    {id="ffff-fff-ffff-ffff-fffffffff"}     []              10       {timeout1="180", timeout2="3600", type="", connid2-val="", sat-enabled=no, namespace=default, nw-uplink="tap0", platform=kvm, timer="300", dest=localhost, dest-port="514"} "0.0.0-1-priv" []  {}         RedHatEnterpriseServer "6.6-Sanity"
  • sed, awk, Perl—take your pick. You could even use ex. – Wildcard Mar 10 '16 at 21:27
  • Why are there 2 lines in the grep output? "nw-uplink" only appears once. Please fix your question. – glenn jackman Mar 10 '16 at 21:31
1

An ugly Awk incantation:

 awk 'BEGIN{RS=" "; FS="="} {gsub(/,|"/,"")} /namespace/ {name=$2}; /uplink/ {intf=$2} END {print name": "intf}' <(command)
 default: tap0
0

Remember that Unix shells are command interpreters, which for convenience when throwing together a few lines to do more complex operations sport control structures and variables. They are not programming languages. Yes, shell scripts are ubiquitous, because they are very portable (some form of shell is available everywhere) and allow to leverage the power of Unix pipelines and (much more importantly) system administration commands strung together.

If you want to do some more delicate maneuvering, use a scripting language like Python (most Linux distributions use it to write all sort of system administration GUIs, so it should be available almost everywhere) or Perl.

0

You could do that with Python and regular expressions:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

# Copyright © 2016 Martin Ueding <dev@martin-ueding.de>
# Licensed under The MIT License

import sys
import re

def main():
    for line in sys.stdin:
        m1 = re.search(r'namespace=([^,]+)', line)
        if m1:
            print(m1.group(1))
        m2 = re.search(r'nw-uplink=([^,]+)', line)
        if m2:
            print(m2.group(1))


if __name__ == '__main__':
    main()

Just pipe the output in there and you will get two lines with the namespace and the interface.

Alternatively one could also try grep --only-matching (or -o) to stamp out the parts one is interested.

Lastly one can also do regular expressions in Bash with =~ (or ~=?) and then use the $BASH_REMATCH array to get the results.

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.