シェルスクリプトの基礎 - ファイル内容を1行ずつ読み込む
ナビゲーションに移動
検索に移動
概要
シェルスクリプトにおいて、while read line文を使用して、ファイル内容を1行ずつ読み込ませるための方法を記載する。
標準入力へリダイレクトさせて読み込む
ファイルを標準入力へリダイレクトさせて、ファイル内容を1行ずつ読み込ませる。
具体的には、list.txtファイルの内容を読み込み、1行ずつechoコマンドで表示させる。
# list.txtファイルの内容 one two three
<syntaxhighlight lang="sh"> #!/bin/bash while read line do echo $line done < ./list.txt </source>
# 出力 one two three
ファイルを変数に格納して読み込む
ファイル内容をcatコマンドで表示させて、それを変数に格納し、ヒアドキュメントを使用して読み込む。
具体的には、list.txtファイル内容を変数DATAに格納して、ヒアドキュメントを使用して変数の内容を読み込む。
# list.txtファイルの内容 one two three
<syntaxhighlight lang="sh"> #!/bin/bash DATA=`cat ./list.txt` while read line do echo $line done << FILE $DATA FILE </source>
# 出力 one two three
catコマンドでファイル内容を表示してパイプで渡す
ファイル内容をcatコマンドで表示させて、その結果をパイプを使用して読み込む。
具体的には、lixt.txtファイルの内容をcatコマンドで表示させて、その結果をパイプでwhile read line文に渡す。
# list.txtファイルの内容 one two three
<syntaxhighlight lang="sh"> #!/bin/bash cat ./list.txt | while read line do echo $line done </source>
# 出力 one two three