wiki:waue/2009/0707

Version 1 (modified by waue, 15 years ago) (diff)

--

shell 裡 for ... in 與 運算 的應用

  • example 1 : 批次殺程序
#!/bin/bash

#str=$(ps axw -eo pid,command | grep "org.apache.catalina.startup.Bootstrap" | grep "start" | awk '{print $1}')

str=$(ps axw -eo pid,command |\
 grep "apache" | grep "start" |\
 awk '{print $1}')
echo "str = $str"

count=1
for i in $str
do
 echo "string[$count]= $i"
 echo "kill -9 $i"
 count=$(($count+1))
done

  • example 2 : 批次改檔名
cd ~
for i in *.[tT][iI][fF]; do
#若目錄內無 .tif 檔案 $i 會傳回 "*.[tT][iI][fF]"
if [ "$i" != "*.[tT][iI][fF]" ]; then
#取得副檔名
subname="`echo $i | awk -F '.' '{print $NF}'`"
#取得主檔名
filename="`echo $i | sed -e s/\.${subname}$//`"
#將 .tif 轉成 .pdf
#tiff2pdf -o "${filename}.pdf" "$i"
mv ${filename}.tif ${filename}.pdf
#若執行成功則刪除 .tif 檔案
if [ $? -eq 0 ]; then
rm -rf $i
fi
fi
done