簡體   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