結構化命令--for學習

for命令

重複執行一系列命令在編程中很常見。通常你需要重複一組命令直至達到某個特定條件,比如處理某個目錄下的所有文件、系統上的所有用戶或是某個文本文件中的所有行。

bash shell提供了for命令,允許你創建一個遍歷一系列值的循環。每個迭代都通過一個該系類中的值執行一組預定義的命令。

for 語法:

for var in list

do

commands

done

實例1:for遍歷目錄

for file in /root/*
do
  if [ -d "$file" ]
  then
     echo "$file is a directory"
  elif [ -f "$file" ]
  then
     echo "$file is a file"
  else
     echo "$file doesn't exist"
  fi
done

輸出結果爲:

/root/1 is a file
/root/anaconda-ks.cfg is a file
/root/cash.sh is a file
/root/chown.sh is a file
/root/Desktop is a directory
/root/evalre.sh is a file
/root/evalsource is a file
/root/format.sh is a file
/root/for.sh is a file
/root/group.sh is a file
/root/hfile is a file
/root/hoststatus.txt is a file
/root/if.sh is a file
/root/install.log is a file
/root/install.log.syslog is a file
/root/iplist is a file
/root/iptest.sh is a file
/root/ntfs-3g_ntfsprogs-2013.1.13 is a directory

心得:for語句可以使用文件擴展匹配來遍歷通配符生成的文件列表,然後它會遍歷列表中的下一個文件。可以將任意多的通配符放進列表中。

實例2:用for循環實現批量修改文件名

1、創建腳本實驗數據
[root@localhost ~]# cd /home/centos/
[root@localhost centos]# touch abc_12345_1_.centos.jpg  abc_12345_2_centos.jpg  abc_12345_3_centos.jpg  abc_12345_4_centos.jpg  abc_12345_5_centos.jpg
2、用for循環遍歷所有.jpg的文件,去除.jpg文件名中centos字符
#!/bin/bash
for file in `ls ./*.jpg` ;do
mv $file `echo $file|sed 's/centos//g'`
done

輸出結果爲:

[root@localhost centos]# ls
abc_12345_1_..jpg  abc_12345_2_.jpg  abc_12345_3_.jpg  abc_12345_4_.jpg  abc_12345_5_.jpg

心得:shell腳本for循環結合sed可以批量更改文件名

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章