ラベル ShellScript の投稿を表示しています。 すべての投稿を表示
ラベル ShellScript の投稿を表示しています。 すべての投稿を表示

2013年2月9日土曜日

[ShellScript]ファイル名の一部を変更する

#!/bin/bash
# ファイル名の一部を変更してコピーする

while [ "$1" != "" ]
do
    # cut コマンド
    # -f1: 1 番目のフィールドを切り出す
    # -d: フィールドの区切りを指定
    name=`echo $1 | cut -f1 -d'.'`
    extension=`echo $1 | cut -f2 -d'.'`
    echo $1 , $name , $extension
    newName=${name}_modify.${extension}
    echo "->" $newName
    cp $1 $newName
    shift # 引数をシフト $2 が $1 へ代入される
done
実行結果
$ ls src/
test01.txt test02.txt test03.txt
$ ./modifyFileName.sh src/*
src/test01.txt , src/test01 , txt
-> src/test01_modify.txt
src/test02.txt , src/test02 , txt
-> src/test02_modify.txt
src/test03.txt , src/test03 , txt
-> src/test03_modify.txt
$ ls src/
test01.txt test02.txt test03.txt
test01_modify.txt test02_modify.txt test03_modify.txt

[ShellScript]ディレクトリ内のファイル名一覧を取得する

#!/bin/bash
# ディレクトリ内のファイル名一覧を取得する

files=`pwd`/src/*
echo ${files}
for filepath in ${files}
do
    echo ${filepath}
done
実行結果
$ ./getFileNames.sh
/home/username/src/test01.txt
/home/username/src/test02.txt
/home/username/src/test03.txt

[ShellScript]for

#!/bin/bash
# for 文
# 与えられた引数の数だけ処理を繰り返す

for arg in $@
do
    echo ${arg}
done
実行結果
$ ./for.sh aaa bbb ccc
aaa
bbb
ccc
$ ./for.sh aaa bbb ccc ddd
aaa
bbb
ccc
ddd

[ShellScript]while

#!/bin/bash
# while 文
# 条件が真である間、処理を繰り返す

i=0
while [ $i -ne 5 ]
do
    # expr: 整数計算をする
    i=`expr $i + 1`
    echo ${i}
done
実行結果
$ ./while.sh
1
2
3
4
5

[ShellScript]変数

#!/bin/bash
# 特殊変数の確認

echo $#
echo $@
echo $0
echo $1
echo $2
echo $3

# 引数をシフトする ($2 -> $1, $3 -> $2, $4 -> $3)
shift
echo $1 , $2 , $3
実行結果
$ ./variables.sh aaa bbb ccc ddd
4
aaa bbb ccc ddd
./variables.sh
aaa
bbb
ccc
bbb , ccc , ddd