[英]Read lines from a file and tokenize each line to extract specific word in shell script
I wrote a shell script to read all lines from a file, tokenized each line to extract particular word.我编写了一个 shell 脚本来读取文件中的所有行,对每一行进行标记以提取特定的单词。 First line is read correct, but from the second line the expected word is not reading correctly.第一行读取正确,但从第二行开始,预期的单词读取不正确。 Looking forward for your suggestions.期待您的建议。
while read -ra line;
do
netmask="${line[5]}"
echo "netmask is $netmask" // first line reading is correct, second line onwards its showing
wrong output
IFS='.' tokens=($netmask)
prefix=0
for i in 0 1 2 3
do
var="${tokens[$i]}"
# i have a logic to calculate number of 1's in the number.
done
done < routes.sh
Contents of route.sh are route.sh 的内容是
route add -net 10.212.220.0 netmask 255.255.255.0 gw 10.213.248.1
route add -net 10.212.220.0 netmask 255.255.128.0 gw 10.213.248.1
Actual output实际产量
netmask is 255.255.255.0
netmask is 128
Expected output预期输出
netmask is 255.255.255.0
netmask is 255.255.128.0
Extra Note:额外注意:
My objective is to (network concept)我的目标是(网络概念)
The problem is that you set IFS='.'
问题是你设置了IFS='.'
, so for the second read
on the array line
will be incorrectly set. ,因此对于阵列line
上的第二次read
将被错误设置。
One way to fix it is by saving the original IFS
and then resetting it when appropriate.修复它的一种方法是保存原始IFS
,然后在适当的时候重置它。 For example,例如,
OldIFS=$IFS
while read -ra line; do
netmask="${line[5]}"
echo "netmask is $netmask"
IFS='.' tokens=($netmask)
prefix=0
for i in 0 1 2 3; do
var="${tokens[$i]}"
done
IFS=$OldIFS
done < routes.sh
You must be careful when changing IFS
, otherwise weird things will happen.更改IFS
时必须小心,否则会发生奇怪的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.