LoginSignup
2
4

More than 1 year has passed since last update.

ShellScriptで複数行のファイルか変数を一行ずつ読み取る

Last updated at Posted at 2021-08-11

while read で ファイルを一行ずつ処理

ファイルを読み取る場合はdoneの後に < とファイルを指定することで1行ずつループができる。

while read line
do
   echo "${line}"
done < sample.txt

while read で 変数を一行ずつ処理

複数行の文字列が格納された変数をループさせたい場合は <<< と3連で記載するのが肝。

while read line
do
   echo "${line}"
done <<< "${var}"

出力結果をパイプで渡す

cat などでファイルを標準出力し、ループにパイプで渡す方法もある。

この記述方法の場合、ループ内での変数の変更がループ外へ反映されないといった不都合があるので、あまりオススメしない。

cat sample.txt | while read line
do
   echo "${line}"
done
2
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4