我对我的请求做了一些改变。为此,请帮助
我有一个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
请帮助
答案 0 :(得分:0)
#!/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
答案 1 :(得分:0)
验证左侧的所有关键字是否存在,如果存在,则将相应的值附加到新文件:
在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
while 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)
$
没有什么可以超越的。