[英]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?例如,我如何匹配 3 个模式(
x_snd_appli, x_route_from_xfer, x_ftp_command
),格式化模式( awk -F"'" '{print $2}'
)并将它们分配给不同的变量?
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.
因此,如果可能,最好使用 AWK/perl。
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.变量的完整内容非常大(大约 45 行) ,当我运行脚本 1x 时,它可能会运行大约 1000 倍。 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.
所以我不想将数据写入文件/循环 10 次以 awk/grep 不同的值并将它们分配给变量。
What you have already is a valid shell script.您已经拥有一个有效的 shell 脚本。 You can just source it:
你可以只获取它:
$ source ./file
$ echo $x_dup_from_xfer
0
To reassign, a little sed/awk can help, for example:要重新分配,一些 sed/awk 可以提供帮助,例如:
$ 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. -n
关闭自动打印行和s
替换, p
打印替换结果。 Multiple sed commands:多个 sed 命令:
$ 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.但是请注意,该 source 和 eval 要求控制文件内容的是您。
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.正如其他人所说,在使用
eval
时,我们最需要注意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.