7. 批量重命名文件 为所有txt文件加上.bak 后缀: 复制代码 代码如下:rename ".txt" ".txt.bak" *.txt 去掉所有的bak后缀: 复制代码 代码如下:rename "*.bak" "" *.bak 把所有的空格改成下划线: 复制代码 代码如下:find path -type f -exec rename "s/ /_/g" {} ; 把文件名都改成大写: 复制代码 代码如下:find path -type f -exec rename "y/a-z/A-Z/" {} ; 8. for/while 循环 复制代码 代码如下: for ((i=0; i < 10; i++)); do echo $i; done for line in $(cat a.txt); do echo $line; done for f in *.txt; do echo $f; done while read line ; do echo $line; done < a.txt cat a.txt | while read line; do echo $line; done
11. 实现Dictionary结构 复制代码 代码如下:hput() { eval "hkey_$1"="$2" } hget() { eval echo "${""hkey_$1""}" } $ hput k1 aaa $ hget k1 aaa 12. 去掉第二列 复制代码 代码如下: $echo "a b c d e f" | cut -d " " -f1,3- $a c d e f
问题就来了,如果我们要将所有的输出都重定向到某个文件呢?我们都不希望每次输出的时候都重定向一下吧,正所谓,山人自有妙计。我们可以用exec 来永久重定向,如下所示: 复制代码 代码如下:#!/bin/bash #redirecting output to different locations exec 2>testerror echo "This is the start of the script" echo "now redirecting all output to another location" exec 1>testout echo "This output should go to testout file" echo "but this should go the the testerror file" >& 2
输出结果如下所示: 复制代码 代码如下:This is the start of the script now redirecting all output to another location lalor@lalor:~/temp$ cat testout This output should go to testout file lalor@lalor:~/temp$ cat testerror but this should go the the testerror file lalor@lalor:~/temp$
以追加的方式重定向: 复制代码 代码如下:exec 3 >> testout 取消重定向: 复制代码 代码如下:exec 3> - 47. 函数 任何地方定义的变量都是全局变量,如果要定义局部变量,需加local 关键字 shell中的函数也可以用递归 复制代码 代码如下:#!/bin/bash function factorial { if [[ $1 -eq 1 ]]; then echo 1 else local temp=$[ $1 - 1 ] local result=`factorial $temp` echo $[ $result * $1 ] fi } result=`factorial 5` echo $result
创建函数库 将函数定一个在另一个文件,然后通过source 命令加载到当前文件 在命令行使用函数 将函数定义在~/.bashrc 中即可 向函数传递数组 复制代码 代码如下: #!/bin/bash #adding values in an array function addarray { local sum=0 local newarray newarray=(`echo "$@"`) for value in ${newarray[*]} do sum=$[ $sum+$value ] done echo $sum } myarray=(1 2 3 4 5) echo "The original array is: ${myarray[*]}" arg1=`echo ${myarray[*]}` result=`addarray $arg1` echo "The result is $result"