1. 程式人生 > >shell讀取檔案的每一行

shell讀取檔案的每一行

寫法一:

----------------------------------------------------------------------------

#!/bin/bash

while read line

do

    echo $line

done < filename(待讀取的檔案)

----------------------------------------------------------------------------

寫法二:

----------------------------------------------------------------------------

#!/bin/bash

cat filename(待讀取的檔案) | while read line

do

    echo $line

done

----------------------------------------------------------------------------

寫法三:

----------------------------------------------------------------------------

for line in `cat filename(待讀取的檔案)`

do

    echo $line

done

----------------------------------------------------------------------------

說明:

for逐行讀和while逐行讀是有區別的,如:

$ cat file

1111

2222

3333 4444 555

$ cat file | while read line; do echo $line; done

1111

2222

3333 4444 555

$ for line in $(<file); do echo $line; done

1111

2222

3333

4444

555