Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Shell 腳本逐行讀檔的三種寫法

在 Shell 裡處理文字檔,最常見的需求就是「一行一行讀進來」。下面用同一份 test.txt 示範三種常見寫法。

#!/bin/bash

printf "*************************************\n"
echo " cat file while read line"
cat test.txt | while read line
do
  echo $line
done

printf "*************************************\n"
echo " while read line <file"
while read line
do
  echo $line
done <test.txt

printf "*************************************\n"
echo " for line in cat test.txt"
SAVEIFS=$IFS
IFS=$(echo -en "\n")
for line in $(cat test.txt)
do
  echo $line
done
IFS=$SAVEIFS

三種方式怎麼挑

第一種用管線把檔案餵給 while,寫法直覺,但 while 會跑在子 shell 中,迴圈內對變數的修改不會保留下來。

第二種用重導向 <file,同樣直覺,而且迴圈跑在目前 shell,變數可以正常帶出來,通常是最推薦的寫法。

第三種用 for 搭配命令替換,關鍵在於先把 IFS 暫存並改成換行符,否則空白會把一行切成好幾段;用完記得用 IFS=$SAVEIFS 還原,避免影響後續程式。

Copyright © Linux教程網 All Rights Reserved