LoginSignup
8
7

More than 5 years have passed since last update.

スペースを含む複数行テキストを、行ごとに処理する

Last updated at Posted at 2016-05-17

次のようなテキストがあるとします。各行にスペースはありません

sample_without_space.txt
12345
67890

行ごとに処理をするには、 for が使えます。 do と done の間にやりたいことを書きます。

$ for i in $(cat sample_without_space.txt"); do echo $i; done
12345
67890
$

上記の例では、各行をただ単に echo しています。

スペースで区切られている文字列のときは

sample_with_space.txt
1 2 3 4 5
6 7 8 9 0

for を使うと、設定によっては(コメントを参照ください)スペースで区切られてしまうため、各行に対して実行することができません

$ for i in $(cat sample_with_space.txt); do echo $i; done
1
2
3
4
5
6
7
8
9
0
$

そこで while read を使うと、スペースで分割されないので、各行ごとに実行することができます

$ cat sample_with_space.txt | while read i; do echo $i; done
1 2 3 4 5
6 7 8 9 0
$
8
7
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
8
7