简体   繁体   English

将awk,sed输出设置为Bash中的变量

[英]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) (第一列ip_local,第二列port_local和最后一列ip_foreign)

All I have to do is to send the awk output to a variable. 我要做的就是将awk输出发送到变量。 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. 我有一个bash脚本,用于处理具有两列的文件。 The first column is the local ip addresses, the other is the one of the foreign addresses. 第一列是本地ip地址,另一列是外部地址之一。

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. 我希望脚本将sed和awk命令的输出分配给我的自定义变量,以分隔IP和端口。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM