繁体   English   中英

如何在Bash脚本中逐行读取文件?

[英]How to read file line by line in Bash script?

我在用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

可能是什么问题呢?

您的代码使我相信您希望每一行都在一个变量中。

尝试以下脚本(我知道可以更轻松,更漂亮地完成此操作,但这是一个简单易读的示例):

#!/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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM