我的请求略有改动。很抱歉这样做,请帮助
我有一个Web UI,用户将在其中传递值,输出将保存到文件中,例如测试,其中包含以下内容。
下面提到的这些值将根据user_input而变化
刚刚在这里举了一个例子
文件测试的内容如下
Gateway oe:value 3.3.3.3
Hostname oe:value test.test.com
IP_Address oe:value 5.5.5.5
Netmask oe:value 255.255.254.0
Primary_DNS oe:value 1.1.1.1
Secondary_DNS oe:value 2.2.2.2
在此示例中,存在六个密钥(网关,主机名,IP_Address,网络掩码,Primary_DNS,Seconday_DNS(。 有时用户可能只填写 4 个文件,然后只有四个关键字。
我正在寻找的是,如果文件测试中存在关键字 Gateway,请将其相应的值与关键字(此处为 Gateway=3.3.3.3(附加到 test1。主机名存在,它应该将值 hostname=test.test.com 附加到 test2。就像所有关键字一样。
Expected output of test1 as per this example
Gateway=3.3.3.3
Expected output of test2
hostname=test.test.com
Expected output of test3
IPADDR=5.5.5.5
Expected output of test4
Netmask=255.255.254.0
Expected output of test5
DNS1=1.1.1.1
Expected output of test6
DNS2=2.2.2.2
请帮忙
#!/bin/bash
ECHO='echo -e'
for field in `cat test | awk {'print $1'}`
do
case "$field" in
Gateway) value=$(cat test | grep -i Gateway | awk {'print $3'})
$ECHO "Gateway=${value}" > test1
;;
Hostname) value=$(cat test | grep -i Hostname | awk {'print $3'})
$ECHO "Hostname=${value}" > test2
;;
IP_Address) value=$(cat test | grep -i IP_Address | awk {'print $3'})
$ECHO "IP_Address=${value}" > test3
;;
Netmask) value=$(cat test | grep -i Netmask | awk {'print $3'})
$ECHO "Netmask=${value}" > test4
;;
Primary_DNS) value=$(cat test | grep -i Primary_DNS | awk {'print $3'})
$ECHO "Primary_DNS=${value}" > test5
;;
Secondary_DNS) value=$(cat test | grep -i Secondary_DNS | awk {'print $3'})
$ECHO "Secondary_DNS=${value}" > test6
;;
esac
done
验证左手边的所有关键字是否存在,如果存在,则将相应的值附加到新文件中:awk 中的解决方案,您首先提供完美的解决方案样本(文件 perfect_set
(,然后用另一组来挑战它:
$ awk 'NR==FNR { # process perfect_set file
if($1 in a); # process each keyword $1 only once
else {
a[$1] # store keyword to memory
c++ # increment counter
}
next # next record
}
$1 in a && a[$1]=="" { # if $1 in latter file in a and seen first time
a[$1]=$0 # set $0 to a[$1]
c-- # decrement counter
}
END { # after processing all files
if(c==0) # if all keywords from perfect_set were found, c==0
for(i in a) # in which case we iterate thru a
print a[i] # and print the records
}' perfect_set questionable_set # > result_set
输出。 print
ing for(i in a)
循环会导致随机输出顺序,因此行标识符保持不变:
IP_Address oe:value 5.5.5.5
Hostname oe:value test.test.com
Netmask oe:value 255.255.254.0
Secondary_DNS oe:value 2.2.2.2
Primary_DNS oe:value 1.1.1.1
Gateway oe:value 3.3.3.3
但是对于一个不完美的集合:
$ awk 'NR==FNR{
# above code not repeated
}' perfect_set <(head -5 perfect_set)
$
不输出任何内容。