0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

bashでテキストファイルを行毎に読み込む

Last updated at Posted at 2020-05-24

目的

bashでテキストファイルを行毎に読み込む処理を、IFSを利用して実装した際の備忘録です。

IFSとは

【シェルスクリプト】IFSで区切り文字(デリミタ)を変更する方法
環境変数「IFS」(Internal Filed Separator)には、bashの場合「スペース」「タブ」「改行」($' \t\n')といった値が初期設定されていて、これらが文字の区切りとして認識されています。

お試し

まず以下のtest.txtを用意します。

test.txt
banana 100 abc
apple  200 xyz

以下のように読み込もうとすると、

test1.sh
for i in `cat test.txt`;
do
    echo $i;
done

スペース区切りで出力されます。

$ ./test1.sh
banana
100
abc
apple
200
xyz

改行区切りで出力したい場合は、以下のようにIFSに改行を指定します。

IFS='                                                                                                                                                  
'
for i in `cat test.txt`;
do
    printf '%s\n' "$i";
done
$ ./test2.sh
banana 100 abc
apple  200 xyz

以下のようにreadを利用しても可能。

while read -r line ;
do
    echo "$line";
done < test.txt
$ ./test3.sh
banana 100 abc
apple  200 xyz

備考

他にもっと良い方法があれば教えていただければ幸いです。

参考

IFSに改行のみを指定したい
readするときはIFS=を付けておくとstrictな感じで気持ちが良い
【シェルスクリプト】IFSで区切り文字(デリミタ)を変更する方法

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?