[英]Not able to correctly read the file in Bash
I have a test.csv file which looks as below 我有一个test.csv文件,如下所示
LOC,IP,D1,D2
abc1,10.13|10.12|10.13|10.14|10.15|10.16,10.11.1.1,11.1.1.23
abc2,12.11|10.15|10.116|10.127|10.110,11.110.8.25,11.11.5.3
abc3,13.21|13.2,10.1.4.50,10.2.7.3
I want to calculate Ipaddress on the target server and then check if the ipaddress
matches the value in test.csv
file. 我想在目标服务器上计算Ipaddress,然后检查
ipaddress
与test.csv
文件中的值匹配。 If it matches then I want to call check_func
and pass values of D1 and D2
to that function. 如果它匹配,那么我想调用
check_func
并将pass values of D1 and D2
给该函数。
So far, I am able to calculate ipaddress
using the following command 到目前为止,我可以使用以下命令计算
ipaddress
host=`uname -n'`
ip_addr=`host $host | awk '{print $NF}'`
Now, I want to do something like below: 现在,我想做类似下面的事情:
case $ip_addr in
10.11|10.12|10.13|10.14|10.15|10.16)
check_func "10.11.1.1" "11.1.1.23"
I have written the following script but it is not giving correct result. 我写了以下脚本,但没有给出正确的结果。 I am always getting the output
Unknown.
我总是得到输出
Unknown.
#! /bin/bash
shopt -s extglob
IFS_backup=$IFS
IFS=,
while read -r column1 column2 column3 column4 ; do
shopt -s extglob
case "$ip_addr" in
@($column2)) check_func "$column3" "$column4" ;;
*) echo Unknown. ;;
esac
done < file.csv
Glob matches need to be exact. 全局匹配需要准确。 A prefix or substring match won't trigger the case clause.
前缀或子字符串匹配不会触发case子句。
So you probably want 所以你可能想要
@($column2)*) check_func "$column3" "$column4" ;;
which effectively accepts a prefix match of any of the alternatives. 它有效地接受任何替代方案的前缀匹配。
By the way, a cleaner way to set IFS
for just the read
statement is 顺便说一下,为
read
语句设置IFS
的更简洁方法是
while IFS=, read -r column1 column2 column3 column4 ; do
That just sets IFS
for the environment of the read
command, so you don't need to worry about it affecting the rest of the script. 这只是为
read
命令的环境设置IFS
,因此您不必担心它会影响脚本的其余部分。
Try something like this instead: 尝试这样的事情:
host=$(uname -n)
awk -F, -v ip_addr="$(host "$host")" '
BEGIN { sub(/.*[[:space:]]/,"",ip_addr) }
{ gsub(/\./,"[.]",$2) }
ip_addr ~ $2 { print $3, $4; f=1 }
END { if (!f) print "Unknown" | "cat>&2" }
' file.csv |
xargs -n 2 check_func
Untested of course since you didn't provide a complete set of sample input/output we could test against but hopefully it's close enough for you to fix if it's not exactly right. 当然未经测试,因为你没有提供一套完整的样本输入/输出我们可以测试,但希望它足够接近你,如果它不完全正确的话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.