无法将sed或awk命令的输出分配给变量?只能打印它们 [英] Unable to assign output of sed or awk command to variables? Can only print them
问题描述
使用此命令从文本文件中提取2行:
cat file1 | grep -A7 SECTIONA | grep -E'Address | BackupAddress'
这会产生下面两行:
地址host1 port_1地址
BackupAddress host2 port_2 BackupAddress
我需要将主机和端口列分配给不同的全局变量,以便稍后在脚本中使用。
hosta =host1
porta =port_1
hostb =host2
portb =port_2
一个成员建议我使用这个,我得到所需的输出,但是我不能在当前shell中使用变量?当我尝试打印或使用它们时,它们显得空白。我也有一个awk解决方案来获得所需的输出,但是sed和awk命令都只是打印上面的内容,并且不会创建变量?
sed -n's / ^ Address * \([^] \ + \)* \([^] \ + \)。* / hosta =\ 1\ nporta = \2/ p;
s / ^ BackupAddress * \([^] \ + \)* \([^] \ + \)。* / hostb =\ 1\\\
portb =\ 2/ p'file1
我可以通过将sed和awk命令分为4部分并运行相同的查询4次,但必须有更好的方法。例如我可以这样做:
hosta =`cat file | sed /或/ awk命令`
porta =`cat file | sed /或/ awk命令`
hostb =`cat file | sed /或/ awk命令`
portb =`cat file | sed /或/ awk命令`
当我使用awk或sed命令执行查询以获得所需输出他们被分配到变量,我可以打印或使用我喜欢的变量;但我不想运行该查询4次。
任何人都可以帮忙请
检查该输入不包含无效字符,则输出可以与evaled相同。在这种情况下,负字符集 [^]
应该被正字符集替换以匹配预期字符。
<$ p $ output = $(sed ...)
eval$ output
或
eval$(sed ...)
或
来源<(sed。 ..)
I use this command to extract 2 lines from a text file:
cat file1 | grep -A7 SECTIONA | grep -E 'Address|BackupAddress'
This produces the two lines below:
Address host1 port_1 Address
BackupAddress host2 port_2 BackupAddress
I need to assign (not print) the host and port columns to distinct global variables to use later in the script.
hosta="host1"
porta="port_1"
hostb="host2"
portb="port_2"
A member suggested I use this and I get the desired output, however I cannot use the variables in the current shell? When I try to print or use them they come out blank. I also have an awk solution to get the desired output, but both sed and awk commands just print the above and do not create the variables?
sed -n 's/^Address *\([^ ]\+\) *\([^ ]\+\).*/hosta="\1"\nporta="\2"/p;
s/^BackupAddress *\([^ ]\+\) *\([^ ]\+\).*/hostb="\1"\nportb="\2"/p' file1
I can get around all this by breaking the sed and awk command into 4 sections and run the same query 4 times but there must be a better way. for example I can do:
hosta=`cat file | sed/or/awk command`
porta=`cat file | sed/or/awk command`
hostb=`cat file | sed/or/awk command`
portb=`cat file | sed/or/awk command`
When I do the query using awk or sed command to get the desired output they get assigned to variables and I can print or use the variables as I like; but I do not want to run the query 4 times.
Can anyone help please
Checking that input doesn't contain invalid character, the output can be sourced same as "eval"ed. in that case negative character set [^ ]
should be replaced by a positive character set to match expected characters
output=$(sed ...)
eval "$output"
or
eval "$(sed ...)"
or
source <(sed ...)
这篇关于无法将sed或awk命令的输出分配给变量?只能打印它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!