问题
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
回答1:
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 ...)
回答2:
this is the case all the time. The host address and port lines are generic across all the files...
...So there are two lines that I grep out of the files and they will always contain 4 variables.
Given the specificity of the application, you could:
- Scan the file once
- Save the results into a variable
- Parse only the variable to assign the host and port variables
Given the input file input.txt, which contains:
Address host1 port_1 Address BackupAddress host2 port_2 BackupAddress
You could use this script:
#!/bin/bash
lines="$(grep -P "Address|BackupAddress" <input.txt)" #Get the two lines needed
hosta="$(awk '/^Address/ { print $2 }' <<<"${lines[@]}")" #Assign $hosta
porta="$(awk '/^Address/ { print $3 }' <<<"${lines[@]}")" #Assign $porta
hostb="$(awk '/^BackupAddress/ { print $2 }' <<<"${lines[@]}")" #Assign $hostb
portb="$(awk '/^BackupAddress/ { print $3 }' <<<"${lines[@]}")" #Assign $portb
#Use the results how you like. Here we just echo them back:
echo "$hosta"
echo "$porta"
echo "$hostb"
echo "$portb"
来源:https://stackoverflow.com/questions/44545583/unable-to-assign-output-of-sed-or-awk-command-to-variables-can-only-print-them