![](/img/trans.png)
[英]how to extract specific lines from file and append it to another existing file in shell script and then delete from original?
[英]Read lines from a file and tokenize each line to extract specific word in shell script
我编写了一个 shell 脚本来读取文件中的所有行,对每一行进行标记以提取特定的单词。 第一行读取正确,但从第二行开始,预期的单词读取不正确。 期待您的建议。
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
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
实际产量
netmask is 255.255.255.0
netmask is 128
预期输出
netmask is 255.255.255.0
netmask is 255.255.128.0
额外注意:
我的目标是(网络概念)
问题是你设置了IFS='.'
,因此对于阵列line
上的第二次read
将被错误设置。
修复它的一种方法是保存原始IFS
,然后在适当的时候重置它。 例如,
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
更改IFS
时必须小心,否则会发生奇怪的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.