Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

bash - Unable to assign output of sed or awk command to variables? Can only print them

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"
porta="2"/p;
s/^BackupAddress *([^ ]+) *([^ ]+).*/hostb="1"
portb="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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ...)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...