最近写脚本,用到数组和循环,从网上摘录了几篇,保存一下。
http://www.cnblogs.com/chengmo/archive/2010/09/30/1839632.html
linux shell在编程方面比windows 批处理强大太多,无论是在循环、运算。已经数据类型方面都是不能比较的。 下面是个人在使用时候,对它在数组方面一些操作进行的总结。
1.数组定义
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ echo $a
1
一对括号表示是数组,数组元素用“空格”符号分割开。
2.数组读取与赋值
- 得到长度:
[chengmo@centos5 ~]$ echo ${#a[@]}
5
用${#数组名[@或*]} 可以得到数组长度
- 读取:
[chengmo@centos5 ~]$ echo ${a[2]}
3
[chengmo@centos5 ~]$ echo ${a[*]}
1 2 3 4 5
用${数组名[下标]} 下标是从0开始 下标是:*或者@ 得到整个数组内容
- 赋值:
[chengmo@centos5 ~]$ a[1]=100
[chengmo@centos5 ~]$ echo ${a[*]}
1 100 3 4 5
[chengmo@centos5 ~]$ a[5]=100
[chengmo@centos5 ~]$ echo ${a[*]}1 100 3 4 5 100
直接通过 数组名[下标] 就可以对其进行引用赋值,如果下标不存在,自动添加新一个数组元素
- 删除:
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ unset a
[chengmo@centos5 ~]$ echo ${a[*]}[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ unset a[1]
[chengmo@centos5 ~]$ echo ${a[*]}
1 3 4 5
[chengmo@centos5 ~]$ echo ${#a[*]}
4
直接通过:unset 数组[下标] 可以清除相应的元素,不带下标,清除整个数据。
3.特殊使用
- 分片:
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ echo ${a[@]:0:3}
1 2 3
[chengmo@centos5 ~]$ echo ${a[@]:1:4}
2 3 4 5
[chengmo@centos5 ~]$ c=(${a[@]:1:4})
[chengmo@centos5 ~]$ echo ${#c[@]}
4
[chengmo@centos5 ~]$ echo ${c[*]}
2 3 4 5
直接通过 ${数组名[@或*]:起始位置:长度} 切片原先数组,返回是字符串,中间用“空格”分开,因此如果加上”()”,将得到切片数组,上面例子:c 就是一个新数据。
- 替换:
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ echo ${a[@]/3/100}
1 2 100 4 5
[chengmo@centos5 ~]$ echo ${a[@]}
1 2 3 4 5
[chengmo@centos5 ~]$ a=(${a[@]/3/100})
[chengmo@centos5 ~]$ echo ${a[@]}
1 2 100 4 5
调用方法是:${数组名[@或*]/查找字符/替换字符} 该操作不会改变原先数组内容,如果需要修改,可以看上面例子,重新定义数据。
从上面讲到的,大家可以发现linux shell 的数组已经很强大了,常见的操作已经绰绰有余了。
============== URL:
http://snailwarrior.blog.51cto.com/680306/154704
BASH 数组用法小结
![](https://i-blog.csdnimg.cn/blog_migrate/79514d00d1bf1d1508c48fdc697b025b.png)
declare -a array
(其实不用声明,按数组方式直接赋值给变量即可,BASH就知道那是数组)
(1) array=(var1 var2 var3 ... varN)
(2) array=([0]=var1 [1]=var2 [2]=var3 ... [n]=varN)
(3) array[0]=var1
arrya[1]=var2
...
array[n]=varN
计算数组元素个数:
${#array[@]} 或者 ${#array[*]}
echo ${array[n]}
filename=(`ls`)
for var in ${filename[@]};do
echo $var
done
n=5
while [ "$i" -lt $n ] ; do
echo "Please input strings ... `expr $i + 1`"
read array[$i]
b=${array[$i]}
echo "$b"
i=`expr $i + 1`
done
chars='abcdefghijklmnopqrstuvwxyz'
for (( i=0; i<26; i++ )) ; do
array[$i]=${chars:$i:1}
echo ${array[$i]}
done
bcd
...
vxy
xyz
yz //没有足够字符串获取了
z //没有足够字符串获取了
重新赋值:(原来的值被重写)
[root@pps ~]# SEASON=("Spring" "Summer" "Autumn" "Winter")
[root@pps ~]# set | grep SEASON
SEASON=([0]="Spring" [1]="Summer" [2]="Autumn" [3]="Winter")
[root@pps ~]# echo ${SEASON[*]} 或者 echo ${SEASON[@]}
Spring Summer Autumn Winter
[root@pps ~]# echo ${SEASON[3]}
Winter
[root@pps ~]# SEASON[0]="New_Spring"
[root@pps ~]# echo ${SEASON[*]}
New_Spring Summer Autumn Winter
[root@pps ~]# unset SEASON[2]
[root@pps ~]# unset SEASON
[root@pps ~]# cat /etc/shells | tr "\n" " " > /tmp/tmp.file
[root@pps ~]# read -a SHELLS < /tmp/tmp.file
[root@pps ~]# set | grep "SHELLS"
SHELLS=([0]="/bin/sh" [1]="/bin/bash" [2]="/sbin/nologin" [3]="/bin/tcsh" [4]="/bin/csh" [5]="/bin/ksh")
=========== URL:
http://justcoding.iteye.com/blog/1963463
linux shell 字符串操作详解 (长度,读取,替换,截取,连接,对比,删除,位置 )
在做shell批处理程序时候,经常会涉及到字符串相关操作。有很多命令语句,如:awk,sed都可以做字符串各种操作。 其实shell内置一系列操作符号,可以达到类似效果,大家知道,使用内部操作符会省略启动外部程序等时间,因此速度会非常的快。
一、判断读取字符串值
表达式 含义
${var} 变量var的值, 与$var相同 ${var-DEFAULT} 如果var没有被声明, 那么就以$DEFAULT作为其值 * ${var:-DEFAULT} 如果var没有被声明, 或者其值为空, 那么就以$DEFAULT作为其值 * ${var=DEFAULT} 如果var没有被声明, 那么就以$DEFAULT作为其值 * ${var:=DEFAULT} 如果var没有被声明, 或者其值为空, 那么就以$DEFAULT作为其值 * ${var+OTHER} 如果var声明了, 那么其值就是$OTHER, 否则就为null字符串 ${var:+OTHER} 如果var被设置了, 那么其值就是$OTHER, 否则就为null字符串 ${var?ERR_MSG} 如果var没被声明, 那么就打印$ERR_MSG * ${var:?ERR_MSG} 如果var没被设置, 那么就打印$ERR_MSG * ${!varprefix*} 匹配之前所有以varprefix开头进行声明的变量 ${!varprefix@} 匹配之前所有以varprefix开头进行声明的变量
加入了“*” 不是意思是: 当然, 如果变量var已经被设置的话, 那么其值就是$var.
二、字符串操作(长度,读取,替换)
表达式 含义
${#string} $string的长度 ${string:position} 在$string中, 从位置$position开始提取子串 ${string:position:length} 在$string中, 从位置$position开始提取长度为$length的子串 ${string#substring} 从变量$string的开头, 删除最短匹配$substring的子串 ${string##substring} 从变量$string的开头, 删除最长匹配$substring的子串 ${string%substring} 从变量$string的结尾, 删除最短匹配$substring的子串 ${string%%substring} 从变量$string的结尾, 删除最长匹配$substring的子串 ${string/substring/replacement} 使用$replacement, 来代替第一个匹配的$substring ${string//substring/replacement} 使用$replacement, 代替所有匹配的$substring ${string/#substring/replacement} 如果$string的前缀匹配$substring, 那么就用$replacement来代替匹配到的$substring ${string/%substring/replacement} 如果$string的后缀匹配$substring, 那么就用$replacement来代替匹配到的$substring
说明:"* $substring”可以是一个正则表达式.
实例:
读取:
- $ echo ${abc-'ok'}
- ok
- $ echo $abc
- $ echo ${abc='ok'}
- ok
- $ echo $abc
- ok
- #如果abc 没有声明“=" 还会给abc赋值。
- $ var1=11;var2=12;var3=
- $ echo ${!v@}
- var1 var2 var3
- $ echo ${!v*}
- var1 var2 var3
- #${!varprefix*}与${!varprefix@}相似,可以通过变量名前缀字符,搜索已经定义的变量,无论是否为空值。
1,取得字符串长度
- string=abc12342341 //等号二边不要有空格
- echo ${#string} //结果11
- expr length $string //结果11
- expr "$string" : ".*" //结果11 分号二边要有空格,这里的:根match的用法差不多
2,字符串所在位置
- expr index $string '123' //结果4 字符串对应的下标是从0开始的
- str="abc"
- expr index $str "a" # 1
- expr index $str "b" # 2
- expr index $str "x" # 0
- expr index $str "" # 0
这个方法让我想起来了js的indexOf,各种语言对字符串的操作方法大方向都差不多,如果有语言基础的话,学习shell会很快的。
3,从字符串开头到子串的最大长度
- expr match $string 'abc.*3' //结果9
个人觉得这个函数的用处不大,为什么要从开头开始呢。
4,字符串截取
- echo ${string:4} //2342341 从第4位开始截取后面所有字符串
- echo ${string:3:3} //123 从第3位开始截取后面3位
- echo ${string:3:6} //123423 从第3位开始截取后面6位
- echo ${string: -4} //2341 :右边有空格 截取后4位
- echo ${string:(-4)} //2341 同上
- expr substr $string 3 3 //123 从第3位开始截取后面3位
- str="abcdef"
- expr substr "$str" 1 3 # 从第一个位置开始取3个字符, abc
- expr substr "$str" 2 5 # 从第二个位置开始取5个字符, bcdef
- expr substr "$str" 4 5 # 从第四个位置开始取5个字符, def
- echo ${str:2} # 从第二个位置开始提取字符串, bcdef
- echo ${str:2:3} # 从第二个位置开始提取3个字符, bcd
- echo ${str:(-6):5} # 从倒数第二个位置向左提取字符串, abcde
- echo ${str:(-4):3} # 从倒数第二个位置向左提取6个字符, cde
上面的方法让我想起了,php的substr函数,后面截取的规则是一样的。
5,匹配显示内容
- //例3中也有match和这里的match不同,上面显示的是匹配字符的长度,而下面的是匹配的内容
- expr match $string '\([a-c]*[0-9]*\)' //abc12342341
- expr $string : '\([a-c]*[0-9]\)' //abc1
- expr $string : '.*\([0-9][0-9][0-9]\)' //341 显示括号中匹配的内容
这里括号的用法,是不是根其他的括号用法有相似之处呢,
6,截取不匹配的内容
- echo ${string#a*3} //42341 从$string左边开始,去掉最短匹配子串
- echo ${string#c*3} //abc12342341 这样什么也没有匹配到
- echo ${string#*c1*3} //42341 从$string左边开始,去掉最短匹配子串
- echo ${string##a*3} //41 从$string左边开始,去掉最长匹配子串
- echo ${string%3*1} //abc12342 从$string右边开始,去掉最短匹配子串
- echo ${string%%3*1} //abc12 从$string右边开始,去掉最长匹配子串
- str="abbc,def,ghi,abcjkl"
- echo ${str#a*c} # 输出,def,ghi,abcjkl 一个井号(#) 表示从左边截取掉最短的匹配 (这里把abbc字串去掉)
- echo ${str##a*c} # 输出jkl, 两个井号(##) 表示从左边截取掉最长的匹配 (这里把abbc,def,ghi,abc字串去掉)
- echo ${str#"a*c"} # 输出abbc,def,ghi,abcjkl 因为str中没有"a*c"子串
- echo ${str##"a*c"} # 输出abbc,def,ghi,abcjkl 同理
- echo ${str#*a*c*} # 空
- echo ${str##*a*c*} # 空
- echo ${str#d*f) # 输出abbc,def,ghi,abcjkl,
- echo ${str#*d*f} # 输出,ghi,abcjkl
- echo ${str%a*l} # abbc,def,ghi 一个百分号(%)表示从右边截取最短的匹配
- echo ${str%%b*l} # a 两个百分号表示(%%)表示从右边截取最长的匹配
- echo ${str%a*c} # abbc,def,ghi,abcjkl
这里要注意,必须从字符串的第一个字符开始,或者从最后一个开始,可以这样记忆, 井号(#)通常用于表示一个数字,它是放在前面的;百分号(%)卸载数字的后面; 或者这样记忆,在键盘布局中,井号(#)总是位于百分号(%)的左边(即前面) 。
7,匹配并且替换
- echo ${string/23/bb} //abc1bb42341 替换一次
- echo ${string//23/bb} //abc1bb4bb41 双斜杠替换所有匹配
- echo ${string/#abc/bb} //bb12342341 #以什么开头来匹配,根php中的^有点像
- echo ${string/%41/bb} //abc123423bb %以什么结尾来匹配,根php中的$有点像
- str="apple, tree, apple tree"
- echo ${str/apple/APPLE} # 替换第一次出现的apple
- echo ${str//apple/APPLE} # 替换所有apple
- echo ${str/#apple/APPLE} # 如果字符串str以apple开头,则用APPLE替换它
- echo ${str/%apple/APPLE} # 如果字符串str以apple结尾,则用APPLE替换它
- $ test='c:/windows/boot.ini'
- $ echo ${test/\//\\}
- c:\windows/boot.ini
- $ echo ${test//\//\\}
- c:\windows\boot.ini
- #${变量/查找/替换值} 一个“/”表示替换第一个,”//”表示替换所有,当查找中出现了:”/”请加转义符”\/”表示。
8. 比较
- [[ "a.txt" == a* ]] # 逻辑真 (pattern matching)
- [[ "a.txt" =~ .*\.txt ]] # 逻辑真 (regex matching)
- [[ "abc" == "abc" ]] # 逻辑真 (string comparision)
- [[ "11" < "2" ]] # 逻辑真 (string comparision), 按ascii值比较
9. 连接
- s1="hello"
- s2="world"
- echo ${s1}${s2} # 当然这样写 $s1$s2 也行,但最好加上大括号
- $ test='c:/windows/boot.ini'
- $ echo ${test#/}
- c:/windows/boot.ini
- $ echo ${test#*/}
- windows/boot.ini
- $ echo ${test##*/}
- boot.ini
- $ echo ${test%/*}
- c:/windows
- $ echo ${test%%/*}
- #${变量名#substring正则表达式}从字符串开头开始配备substring,删除匹配上的表达式。
- #${变量名%substring正则表达式}从字符串结尾开始配备substring,删除匹配上的表达式。
- #注意:${test##*/},${test%/*} 分别是得到文件名,或者目录地址最简单方法。
再加上一个参数处理的,URL如下:
http://www.cnblogs.com/FrankTan/archive/2010/03/01/1634516.html
0.引言
写程序的时候经常要处理命令行参数,本文描述在Bash下的命令行处理方式。
选项与参数:
如下一个命令行:
我们称-f为选项,它需要一个参数,即config.conf, -v 也是一个选项,但它不需要参数。
--prefix我们称之为一个长选项,即选项本身多于一个字符,它也需要一个参数,用等号连接,当然等号不是必须的,/home可以直接写在--prefix后面,即--prefix/home,更多的限制后面具体会讲到。
在bash中,可以用以下三种方式来处理命令行参数,每种方式都有自己的应用场景。
* 手工处理方式
* getopts
* getopt
下面我们依次讨论这三种处理方式。
1. 手工处理方式
在手工处理方式中,首先要知道几个变量,还是以上面的命令行为例:
* $0 : ./test.sh,即命令本身,相当于C/C++中的argv[0]
* $1 : -f,第一个参数.
* $2 : config.conf
* $3, $4 ... :类推。
* $# 参数的个数,不包括命令本身,上例中$#为4.
* $@ :参数本身的列表,也不包括命令本身,如上例为 -f config.conf -v --prefix=/home
* $* :和$@相同,但"$*" 和 "$@"(加引号)并不同,"$*"将所有的参数解释成一个字符串,而"$@"是一个参数数组。如下例所示:
2
3 for arg in " $* "
4 do
5 echo $arg
6 done
7
8 for arg in " $@ "
9 do
10 echo $arg
11 done
12
执行./test.sh -f config.conf -n 10 会打印:
-f config.conf -n 10 #这是"$*"的输出
-f #以下为$@的输出
config.conf
-n
10
所以,手工处理的方式即对这些变量的处理。因为手工处理高度依赖于你在命令行上所传参数的位置,所以一般都只用来处理较简单的参数。如
./test.sh 10
而很少使用./test -n 10这种带选项的方式。 典型用法为:
if [ x$ 1 != x ]
then
#...有参数
else
then
#...没有参数
fi
为什么要使用 x$1 != x 这种方式来比较呢?想像一下这种方式比较:
if [ -n $1 ] #$1不为空
但如果用户不传参数的时候,$1为空,这时 就会变成 [ -n ] ,所以需要加一个辅助字符串来进行比较。
手工处理方式能满足大多数的简单需求,配合shift使用也能构造出强大的功能,但在要处理复杂选项的时候建议用下面的两种方法。
2. getopts/getopt
处理命令行参数是一个相似而又复杂的事情,为此,C提供了getopt/getopt_long等函数,
C++的boost提供了Options库,在shell中,处理此事的是getopts和getopt.
getopts和getopt功能相似但又不完全相同,其中getopt是独立的可执行文件,而getopts是由Bash内置的。
先来看看参数传递的典型用法:
* ./test.sh -a -b -c : 短选项,各选项不需参数
* ./test.sh -abc : 短选项,和上一种方法的效果一样,只是将所有的选项写在一起。
* ./test.sh -a args -b -c :短选项,其中-a需要参数,而-b -c不需参数。
* ./test.sh --a-long=args --b-long :长选项
我们先来看getopts,它不支持长选项。
使用getopts非常简单:
代码
# !/ bin / bash
while getopts " a:bc " arg #选项后面的冒号表示该选项需要参数
do
case $arg in
a)
echo " a's arg:$OPTARG " #参数存在$OPTARG中
;;
b)
echo " b "
;;
c)
echo " c "
;;
? ) #当有不认识的选项的时候arg为 ?
echo " unkonw argument "
exit 1
;;
esac
done
现在就可以使用:
./test.sh -a arg -b -c
或
./test.sh -a arg -bc
来加载了。
应该说绝大多数脚本使用该函数就可以了,如果需要支持长选项以及可选参数,那么就需要使用getopt.
下面是getopt自带的一个例子:
# !/ bin / bash
# A small example program for using the new getopt( 1 ) program.
# This program will only work with bash( 1 )
# An similar program using the tcsh( 1 ) script language can be found
# as parse.tcsh
# Example input and output (from the bash prompt):
# . / parse.bash - a par1 ' another arg ' -- c - long ' wow!*\? ' - cmore - b " very long "
# Option a
# Option c, no argument
# Option c, argument `more '
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1 '
# --> `another arg '
# --> `wow !* \ ? '
# Note that we use ` " $@ "' to let each command-line parameter expand to a
# separate word. The quotes around `$@ ' are essential!
# We need TEMP as the `eval set -- ' would nuke the return value of getopt.
# - o表示短选项,两个冒号表示该选项有一个可选参数,可选参数必须紧贴选项
#如 - carg 而不能是 - c arg
# -- long表示长选项
# " $@ " 在上面解释过
# - n:出错时的信息
# -- :举一个例子比较好理解:
#我们要创建一个名字为 " -f " 的目录你会怎么办?
# mkdir - f #不成功,因为 - f会被mkdir当作选项来解析,这时就可以使用
# mkdir -- - f 这样 - f就不会被作为选项。
TEMP = `getopt - o ab:c:: -- long a - long ,b - long :,c - long :: \
- n ' example.bash ' -- " $@ " `
if [ $ ? != 0 ] ; then echo " Terminating... " >& 2 ; exit 1 ; fi
# Note the quotes around `$TEMP ' : they are essential!
# set 会重新排列参数的顺序,也就是改变$ 1 ,$ 2 ...$n的值,这些值在getopt中重新排列过了
eval set -- " $TEMP "
#经过getopt的处理,下面处理具体选项。
while true ; do
case " $1 " in
- a |-- a - long ) echo " Option a " ; shift ;;
- b |-- b - long ) echo " Option b, argument \`$2' " ; shift 2 ;;
- c |-- c - long )
# c has an optional argument. As we are in quoted mode,
# an empty parameter will be generated if its optional
# argument is not found.
case " $2 " in
"" ) echo " Option c, no argument " ; shift 2 ;;
* ) echo " Option c, argument \`$2' " ; shift 2 ;;
esac ;;
-- ) shift ; break ;;
* ) echo " Internal error! " ; exit 1 ;;
esac
done
echo " Remaining arguments: "
for arg do
echo ' --> '" \`$arg' " ;
done
比如我们使用
./test -a -b arg arg1 -c
你可以看到,命令行中多了个arg1参数,在经过getopt和set之后,命令行会变为:
-a -b arg -c -- arg1
$1指向-a,$2指向-b,$3指向arg,$4指向-c,$5指向--,而多出的arg1则被放到了最后。
3.总结
一般小脚本手工处理也许就够了,getopts能处理绝大多数的情况,getopt较复杂,功能也更强大。
有问题请指出,不胜感激。
====== 还有一个,URL如下:
http://hi.baidu.com/woailiuxiaomi/item/135490c486f6120b515058a0
linux shell:for循环遇到的空格问题
这问题以前就曾碰到,今天又遇上了,记录一下:
有一包含数行的文本文件1.txt,单词之间以空格隔开,如:
[op@oradb ~]$ cat 1.txt
a b c
d e f
g h i
需要对文件逐行处理,刚开如用for,如
for i in `cat 1.txt`;do echo $i|awk '{print "***",$0}';done
这时的输出如下:
*** a
*** b
*** c
*** d
*** e
*** f
*** g
*** h
*** i
而不是所期望的--
*** a b c
*** d e f
*** g h i
解决方法:
(1)用while read
[op@oradb ~]$while read i; echo $i|awk '{print "***",$0}'; done<1.txt
*** a b c
*** d e f
*** g h i
(2)更改IFS
将shell的IFS改成任意字符
[op@oradb ~]$ (IFS=':';for i in `cat 1.txt`;do echo $i|awk '{print "***",$0}';done)
*** a b c
*** d e f
*** g h i