简体   繁体   中英

Assigning output columns from multiple lines to distinct variables?

Below you find output of my awk and sed commands that I use to extract 2 lines output from an xml file. I have to assign the host-names and port-names to 4 distinct variables so I can use these to do further inquires. Can you assist?

cat file | awk | sed produces two lines below

Address host1  port_1  Address
BackupAddress host2 port_2  BackupAddress

Desired output

hosta="host1"
porta="port_1"
hostb="host2"
portb="port_2"

I would appreciate and welcome a detailed explanation with your resolution.

Use awk:

awk '
  /^Address/       { print "hosta=\""$2"\"\nporta=\""$3"\"" }
  /^BackupAddress/ { print "hostb=\""$2"\"\nportb=\""$3"\"" }' file

or, use a variable to hold the double quote to reduce clutter:

awk -v q='"' '
  /^Address/       { print "hosta="q$2q"\nporta="q$3q }
  /^BackupAddress/ { print "hostb="q$2q"\nportb="q$3q }' file

I am not sure what code you are using currently. If you have already written it in awk, you could probably incorporate the above logic there as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM