shell 逐行讀取檔案的內容

2021-06-14 03:31:30 字數 979 閱讀 3276

說明:shell 逐行讀取文字檔案內容。

示例:讀取 /etc/passwd 檔案內容。

1:[python]view plain

copy

#! /bin/bash

ifs="  

"  n=0

forline 

in`cat /etc/passwd`  

do  

n=`expr $n + 1

`  echo -e "$n/t$line"

done   2:

[python]view plain

copy

#! /bin/bash

n=0while

read line  

do  

n=`expr $n + 1

`  echo -e "$n/t$line"

done < /etc/passwd  

[python]view plain

copy

#! /bin/bash

n=0cat /etc/passwd | while

read line  

do        

n=`expr $n + 1

`  echo -e "$n/t$line"

done   3:

[python]view plain

copy

#! /bin/bash

n=1r=`cat /etc/passwd | wc -l`  

while

[ $n -le $r ]  

do  

echo -e "$n/t$(echo `head -$n /etc/passwd | tail -1`)"

n=`expr $n + 1

`  done  

Shell指令碼逐行讀取檔案

方法1 while迴圈中執行效率最高,最常用的方法。while read line doecho line done filename 注釋 這種方式在結束的時候需要執行檔案,就好像是執行完的時候再把檔案讀進去一樣。方法2 管道法 cat filename while read line cat f...

Shell指令碼從檔案中逐行讀取內容的幾種方法例項

從檔案逐行讀取資料的方法有兩種,一種是在while迴圈或until迴圈中使用read命令,通過檔案描述符一行一行的讀取檔案內容 另一種是在for迴圈中使用cat 來讀取檔案的內容。1.使用for迴圈從檔案中逐行讀取內pplzjtmh容 在預設情況現下此方法是逐個單詞的讀取檔案內容,因為使用這種方法讀...

如何用Shell逐行讀取檔案

在學習linux shell scripts時,乙個最常見的錯誤就是用for for line in cat file.txt do 迴圈逐行讀取檔案。下面的例子可以看出這樣做的結果。檔案file.txt內容 cat file.txt this is the row no 1 this is the...