如何在「讀取時」中從特定行數開始讀取檔案?

如何在「讀取時」中從特定行數開始讀取檔案?

我想要的就是像這樣指定一定數量的行lineNumberIs=3,並告訴讀取時從第三行開始或從什麼行號開始,並在之後獲取行以稍後在獲取的行上執行一些命令 類似的東西

 while read line from $lineNumberIs
    do
    **some commands not just echo nor printing on the screen** 
    done < $dataFile

答案1

while IFS= read -r line; do
    # ...
done < <(tail -n "+$lineNumberIs" $dataFile)

tail -n +K(帶有加號)告訴 tail 從指定的行號開始(參見手冊頁)。

<(...)位是一個流程替代。它允許您指定一個命令序列,並讓 bash 像讀取檔案一樣讀取它。當您想要避免在管道中建立的子 shell 的影響時,它非常方便。

IFS= read -r用於精確讀取檔案中出現的行,不刪除空格或轉義序列。

答案2

#!/bin/bash
if [ $# -eq 0 ]; then
        echo "Please execute $0 with linestoskip parameter"
        exit 0
fi
linestoskip=$1
Counter=0
dataFile='/etc/fstab'
while read line
do
        if [ $Counter -ge $linestoskip ]; then
                echo $line
        fi
        Counter=`expr $Counter + 1`
done < $dataFile

該腳本需要跳過的行數作為參數。你可以在內部 if 條件下做任何你想做的事情。

答案3

非常簡單的解決方案 -

tail -n +K filename

其中 K = 要讀取檔案的行號。這將從第 K 行開始讀取檔案到末尾。

相關內容