LoginSignup
1

More than 3 years have passed since last update.

シェルスクリプト テーブル形式っぽく出力する

Last updated at Posted at 2020-01-17

最初に変数 output にフィールド名をスペース区切りで格納しておきます。
改行したい位置には、$'\n' をセットします。
後は各フィールドの値をスペース区切りでセットしていきます。
出力時には printf で書式を指定しています。

table_output.sh
students=("1 Tom 70" "2 Keiko 80" "3 Peter 65" "4 Risa 100")
output="id name score"

for student in "${students[@]}"
do
  set -- $student
  output="${output}"$'\n'"$1 $2 $3"
done
# 書式指定なし
echo "${output}"
# 書式指定あり
echo "${output}" | awk '{printf "%-5s|%-10s|%-5s\n",$1,$2,$3}'
書式指定なし
id name score
1 Tom 70
2 Keiko 80
3 Peter 65
4 Risa 100  
書式指定あり
id   |name      |score
1    |Tom       |70   
2    |Keiko     |80   
3    |Peter     |65   
4    |Risa      |100

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
1