2017-07-15 87 views
0

我用bash脚本逐行读取文件时遇到了问题。下面是该脚本:如何在Bash脚本中逐行读取文件?

#!/bin/bash 

file="cam.txt" 

while IFS=: read -r xf1 xf2 xf3 
do 
    printf 'Loop: %s %s %s\n' "$xf1" "$xf2" "$xf3" 
    f1=$xf1 
    f2=$xf2 
    f3=$xf3 
done < $file 
printf 'After: %s %s %s\n' "$f1" "$f2" "$f3" 

这里是cam.txt

192.168.0.159 
554 
554 

这里是输出:

Loop: 192.168.0.159 
Loop: 554 
Loop: 554 
After: 554 

可能是什么问题呢?

+0

显示你的文件的样本。 – Mat

+0

我加了。感谢您的关注@Mat – voyvoda

+1

现在还不清楚你想要做什么。输出与您的代码和输入文件相同。请更详细地解释你想要达到的目标。 – Mat

回答

-1

你的代码让我相信你想让每一行变成一个变量。

试试这个脚本(我知道这是可以做到更轻松,更漂亮,但这是一个简单易读的例子):

#!/bin/bash 
file="cam.txt" 

while read -r line 
do 
    printf 'Line: %s\n' "$line" 

    current=$line 
    last=$current 
    secondlast=$last 

    printf 'Loop: %s %s %s\n' "$current" "$last" "$secondlast" 
done < $file 

printf 'After: %s %s %s\n' "$current" "$last" "$secondlast" 

简单的版本:

{ read -r first; read -r second; read -r third; } <cam.txt 
printf 'After: %s %s %s\n' "$first" "$second" "$third"