简体   繁体   中英

Set an awk,sed output to a variable in Bash

UPDATE: Now I have a simpler file to handle, similar to this:

127.0.0.1 25 127.0.0.1
127.0.0.1 25 127.0.0.1
127.0.0.1 32828 127.0.0.1
127.0.0.1 32830 127.0.0.1
127.0.0.1 32906 127.0.0.1
127.0.0.1 32908 127.0.0.1
127.0.0.1 32984 127.0.0.1

(first column ip_local, second column port_local and last column ip_foreign)

All I have to do is to send the awk output to a variable. The code I managed to write is this, but I still have problems to process the text file...

#!/bin/sh
for i in `cat DEV0_IPsListSep.txt`;
do
ip_local=$(awk '{print $1}' $i);
port_local=$(awk '{print $2}' $i);
ip_foreign=$(awk '{print $3}' $i);
if [$port_local < 3200] ||  [$ip_foreign != 127.0.0.1] || [$ip_foreign != 
192.168.1.1]
then
echo $ip_foreign >> IPFinalList.txt;
fi
done

I have a bash script that processes a file with two columns. The first column is the local ip addresses, the other is the one of the foreign addresses.

Example:

127.0.0.1:25 127.0.0.1:33862
127.0.0.1:25 127.0.0.1:36498
127.0.0.1:25 127.0.0.1:37338
127.0.0.1:25 127.0.0.1:37410
127.0.0.1:25 127.0.0.1:38320
127.0.0.1:25 127.0.0.1:39428
127.0.0.1:25 127.0.0.1:39514
127.0.0.1:25 127.0.0.1:39768
127.0.0.1:25 127.0.0.1:39846
127.0.0.1:25 127.0.0.1:40376

I would like the script to assign the outputs of sed and awk commands to my custom variables, to separate IPs and ports.

I tried to create a script but still receive syntax errors...

#!/bin/sh

for i in `IPslist.txt`;

ipLocal=$(awk '{print $1}' | sed -e 's/:.*//' $i)
portLocal=$(awk '{print $1}' | sed -e 's/.*://' $i)
ipForeign=$(awk '{print $2}' | sed -e 's/:.*//' $i)
portForeign=$(awk '{print $2}' | sed -e 's/.*://' $i)

if [ $portLocal < 3200 ] ||  [ $ipForeign != 127.0.0.1 ] || [ 
$ipForeign != 192.168.1.1 ]

then

echo $ipForeign >> IPFinalList.txt

fi

使用单个awk流程(优化解决方案):

awk -F':|[[:space:]]+' '$2<3200 || $3!= 127.0.0.1 || $3!= 192.168.1.1' IPslist.txt > IPFinalList.txt

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