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

时间:2021-06-29 01:47:51

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?

可能是什么问题呢?

1 个解决方案

#1


-1  

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"

#1


-1  

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"