0
1

More than 1 year has passed since last update.

【Linux】スペースを含む文字列を行単位で繰返し処理する

Posted at

readを使用

以下のように記述するとスペースを含む文字列を行単位で繰り返し処理できます。

sample.sh
data=$( cat <<-EOF
    ai 12
    ue 34
    oo 55
EOF
)

while read line
do
  echo $line
done < <(echo "$data")
$ bash sample.sh
ai 12
ue 34
oo 55

また以下のようなこともできます。

sample.sh
data=$( cat <<-EOF
      ai 12
      ue 34
EOF
)
while read -a line
do
  echo '行全体'
  echo ${line[*]}
  echo '最初の単語'
  echo ${line[0]}
  echo '2番目の単語'
  echo ${line[1]}
done < <(echo "$data")
$ bash test.sh
--行全体--
ai 12
--最初の単語--
ai
--2番目の単語--
12
--行全体--
ue 34
--最初の単語--
ue
--2番目の単語--
34

IFSを変更

以下のように記述してもスペースを含む文字列を行単位で繰り返し処理できます。

sample.sh
data=$( cat <<-EOF
      ai 12
      ue 34
      oo 55
EOF
)

IFS_BACKUP=$IFS
IFS=$'\n'
for line in $data
do
  echo $line
done
IFS=$IFS_BACKUP
$ bash sample.sh
ai 12
ue 34
oo 55
0
1
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
1