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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45116966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:17:18  来源:igfitidea点击:

How to read file line by line in Bash script?

linuxbashfileio

提问by voyvoda

I have a problem with reading a file line by line with bash script. Here is the 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"

Here is cam.txt:

这是cam.txt

192.168.0.159
554
554

Here is the output:

这是输出:

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

What could be the problem?

可能是什么问题呢?

采纳答案by Lukas Isselb?cher

Your code leads me to believe you want each line in one variable.

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

Try this script (I know this can be done easier and prettier, but this is a simple and readable example):

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

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

Simpler version:

更简单的版本:

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