简体   繁体   中英

Bash AWK find multiple patterns and assign to different variables

I currently have a variable containing values resembling this:

x_snd_user=''
x_snd_appli=''
x_snd_text=''
x_rcv_user=''
x_rcv_appli=''
x_rcv_text=''
x_dup_from_xfer='0'
x_route_from_xfer='0'
x_route_to_xfer='0'
x_reply_by_xfer='0'
x_reply_to_xfer='0'
x_routed_to_XIB='N'
x_end_xfer_script=''
x_ftp_command=''

How can I, for example, match 3 patterns ( x_snd_appli, x_route_from_xfer, x_ftp_command ), format the patterns ( awk -F"'" '{print $2}' ) and assign them to different variables?

For example, I've got variables and want to assign the output to these:

 - Application= The value of <x_snd_appli>
 - Route= The value of <x_route_from_xfer>
 - Command= The value of <x_ftp_command>

Preferably not with something that needs to be installed as that's not possible. So with AWK/perl if that's possible would be preferred.

The complete content of the variable is pretty big (about 45 lines) and it's possible that this runs about 1000x when I run the script 1x. So I don't want to write data to a file/loop over it 10 times to awk/grep different values and assign them to variables.

What you have already is a valid shell script. You can just source it:

$ source ./file
$ echo $x_dup_from_xfer
0

To reassign, a little sed/awk can help, for example:

$ eval $(sed -n 's/^x_route_from_xfer=/Route=/p' file)
$ echo $Route
0

-n turns off automatic printing of lines and s substitutes, p prints the substitution result. Multiple sed commands:

$ eval $(sed -n 's/^x_route_from_xfer=/Route=/p;s/.../.../p' file)

Take care however, that source and eval require that it's you who controls the file contents.

The input may also come from a variable:

eval $(sed ... <<< "$var")

How about:

#!/bin/bash

transfer="
x_snd_user=''
x_snd_appli=''
x_snd_text=''
x_rcv_user=''
x_rcv_appli=''
x_rcv_text=''
x_dup_from_xfer='0'
x_route_from_xfer='0'
x_route_to_xfer='0'
x_reply_by_xfer='0'
x_reply_to_xfer='0'
x_routed_to_XIB='N'
x_end_xfer_script=''
x_ftp_command=''
"
# or assign "transfer" with a output of other command.

while read -r line; do
    eval "$line"
done < <(
awk -F= 'BEGIN {
    a["x_snd_appli"] = "Application"
    a["x_route_from_xfer"] = "Route"
    a["x_ftp_command"] = "Command"
    }
    a[$1] {print a[$1] "=" $2}
' <<< "$transfer"
)

echo "Application=$Application"
echo "Route=$Route"
echo "Command=$Command"

We need to pay most attention when using eval as others mention.

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