簡體   English   中英

Bash:使用sed或awk讀取文件方案中的行

[英]Bash: Read lines in a file scenario with sed or awk

我有這樣的場景:

文件內容:

10.1.1.1
10.1.1.2
10.1.1.3
10.1.1.4

我想要sed或awk,以便每當我返回新行時捕獲文件。

喜歡

第一次迭代:

cat ip | some magic
10.1.1.1

Second iteration returns
10.1.1.2
Third iteration returns
 10.1.1.3
Fourth iteration returns
10.1.1.4

經過n次迭代后,返回第1行

第五次迭代返回:

10.1.1.1

我們可以使用sed或awk來做到這一點。

你不能用貓做這件事。 你也不能在管道上尋找,所以你不能使用管道..

您可以使用嵌套的while循環執行此操作

while ((1))
do
    while read line
    do
       echo "$line"
    done <somefile
done

您需要將行號存儲在文件中,並在每次調用時使用模數遞增。

get_line () {
    if [[ ! -e /var/local/get_line.next ]]
    then
        if [[ ! -e /var/local ]]
        then
            mkdir -p /var/local
        fi
        line_no=1
    else
        line_no=$(< /var/local/get_line.next)
    fi
    file_length=(wc -l < ip_file)
    if ((file_length == 0))
    then
        echo "Error: Data file is empty" >&2
        return 1
    fi
    if ((line > file_length))
    then
        line=1
    fi
    sed -n "$line_no{p;q}" ip_file
    echo "$((++line_no))" > /var/local/get_line.next
}

這是一個函數的形式,您可以將其合並到腳本中。 隨意更改get_line.next文件的位置。 請注意,如有必要,權限需要正確才能讀取或寫入文件或創建目錄。

你不需要使用cat

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM