【问题标题】:How to read file line by line in Bash script?如何在 Bash 脚本中逐行读取文件?
【发布时间】:2017-12-20 09:08:54
【问题描述】:

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

可能是什么问题?

【问题讨论】:

  • 显示文件样本。
  • 我添加了。感谢您的关注@Mat
  • 现在还不清楚您要做什么。给定您的代码和输入文件,输出与预期一致。请更详细地说明您要达到的目标。
  • 试试这个:{ read -r xf1; read -r xf2; read -r xf3; } &lt;cam.txt
  • @Cyrus,令人印象深刻的读心术

标签: linux bash file io


【解决方案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"

【讨论】:

    猜你喜欢
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 2013-03-07
    • 2013-10-04
    相关资源
    最近更新 更多