長い文字列を複数行に分割し、Linux bashスクリプトで変数に割り当てる方法

長い文字列を複数行に分割し、Linux bashスクリプトで変数に割り当てる方法

長い文字列値を持つ変数を含むbashスクリプトを作成しようとしています。文字列を複数行に分割するとエラーが発生します。文字列を複数行に分割して変数に代入するには?

ベストアンサー1

配列の複数の部分文字列に長い文字列を割り当てると、コードがより美しくなります。

#!/bin/bash

text=(
    'Contrary to popular'
    'belief, Lorem Ipsum'
    'is not simply'
    'random text. It has'
    'roots in a piece'
    'of classical Latin'
    'literature from 45'
    'BC, making it over'
    '2000 years old.'
)

# output one line per string in the array:
printf '%s\n' "${text[@]}"

# output all strings on a single line, delimited by space (first
# character of $IFS), and let "fmt" format it to 45 characters per line
printf '%s\n' "${text[*]}" | fmt -w 45

逆にします。つまり、長い行を複数行に分割し、配列変数として読み込みます。

$ cat file
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.

fmtここでは、行を最大30文字の短い行に分割し、シェルからこの行を次の名前の配列として読み込みreadarrayます。bashtext

$ readarray -t text < <(fmt -w 30 file)

これで、行グループまたは各個々の行にアクセスできます。

$ printf '%s\n' "${text[@]}"
Contrary to popular belief,
Lorem Ipsum is not simply
random text. It has roots in a
piece of classical Latin
literature from 45 BC, making
it over 2000 years old.
$ printf '%s\n' "${text[3]}"
piece of classical Latin

(配列は0から始まりますbash。)

おすすめ記事