今回、shellスクリプトを使って行うデータ処理は以下の通り
mae1.dat1~mae9000.dat1という9000個のファイルがあって、
mae*.dat1というファイルの中身が
------------------------
1gyome
id x y z
1 1.11 1.21 1.30
2 1.21 1.51 3.13
3 3.32 5.11 6.98
4 2.12 7.77 7.87
------------------------
を、4行目以下のデータの1列目と4列目だけを取り出して
------------------------
1 1.30
2 3.13
3 6.98
4 7.87
------------------------
名前をato00001.dat2~ato09000.dat2に変換するデータ処理である。
-------------------------------------------------------------------------------------------
#!/bin/sh
echo "datasyori script"
b=mae
c=ato
e=.dat1
h=.dat2
i=1
while [ $i -le 9000 ]
do
if [ "$i" -lt 10 ]
then
num=0000${i}
elif [ "$i" -lt 100 ]
then
num=000${i}
elif [ "$i" -lt 1000 ]
then
num=00${i}
else
num=0${i}
fi
f=${b}${i}${e}
g=${c}${num}${h}
echo "${f}"
awk 'NR>3 {print $1,$4}' ${f}>${g}
i=`expr $i + 1`
done
------------------------------------------------------------------------------------
shell scriptの中身を1つ1つ説明していくと、
-------------------------------------------------------------------------------------------
#!/bin/sh #!/bin/shはshellスクリプトを動かしはじめるために絶対必要。
echo "datasyori script" echoで" "内の言葉をターミナルに表示させる。
b=mae 変数bにmaeを代入する
c=ato 変数cにatoを代入する
e=.dat1 変数eに.dat1を代入する
h=.dat2 変数hに.dat2を代入する
i=1 変数iに1を代入する
while [ $i -le 9000 ] while[] do ○○○ doneで○○○を[]内の条件になるまで繰り返す
[ $i -le 9000 ]は、$iが9000以下という条件である。
$iはiの数字である。
後ろの方にi=`expr $i + 1`と書かれており、○○○を繰り返すたびに、
iの数字が1増えていき、i=2,i=3・・・となる。
A -le Bは、AはB以下であるという意味。
do
if [ "$i" -lt 10 ] if[A] then ○○○ elif[B] then ××× else △△△ fi
Aという条件の時は○○○ を行い、
Aでなく、Bという条件の時、×××を行い、
Aでも、Bでもない時、△△△を行う
A -lt Bは、AはBより小さいという意味である。
then
num=0000${i} i=2の時、変数numに00002を代入する。
elif [ "$i" -lt 100 ]
then
num=000${i}
elif [ "$i" -lt 1000 ]
then
num=00${i}
else
num=0${i}
fi
f=${b}${i}${e} 変数fに変数bと変数iと変数eを結合したものを代入
ここでは、変数fはmae*.dat1となる。
g=${c}${num}${h} ここでは、変数gはato*.dat2となる。
echo "${f}" ここでは、mae*.dat1をターミナルに書き出す
awk 'NR>3 {print $1,$4}' ${f}>${g} mae*.dat1の3行目以降の1列目と4列目を取り出したデー タをato*.dat2として保存
i=`expr $i + 1` i=`expr $i + 1`はiに1を足すという意味である。
done
------------------------------------------------------------------------------------
shellスクリプトで変数を扱う時、注意が必要である。
-----------
sponsored link
-----------
変数iがあって、それを文字として扱いたいときは${i}、
足し算などができるように数字として扱いたいときは$iとする。
また、whileの[]内では$i、ifの[]内では"$i"としたらうまくデータ処理ができた。
なぜだかはわからない。
この変数の扱いが難しいから、僕はshellスクリプトが好きではない。