您的位置:首页 > 运维架构 > Shell

[Linux]:bash shell字符串的截取

2011-09-24 22:29 513 查看
shell字符串的截取的问题:

一、Linux shell 截取字符变量的前8位,有方法如下:

1.expr substr “$a” 1 8

2.echo $a|awk ‘{print substr(,1,8)}’

3.echo $a|cut -c1-8

4.echo $

5.expr $a : ‘\(.\\).*’

6.echo $a|dd bs=1 count=8 2>/dev/null

二、按指定的字符串截取

1、第一种方法:

${varible##*string} 从左向右截取最后一个string后的字符串

${varible#*string}从左向右截取第一个string后的字符串

${varible%%string*}从右向左截取最后一个string后的字符串

${varible%string*}从右向左截取第一个string后的字符串

“*”只是一个通配符可以不要

例子:

$ MYVAR=foodforthought.jpg

$ echo ${MYVAR##*fo}

rthought.jpg

$ echo ${MYVAR#*fo}

odforthought.jpg

2、第二种方法:${varible:n1:n2}:截取变量varible从n1到n2之间的字符串。

可以根据特定字符偏移和长度,使用另一种形式的变量扩展,来选择特定子字符串。试着在 bash 中输入以下行:

$ EXCLAIM=cowabunga

$ echo ${EXCLAIM:0:3}

cow

$ echo ${EXCLAIM:3:7}

abunga

这种形式的字符串截断非常简便,只需用冒号分开来指定起始字符和子字符串长度。

三、按照指定要求分割:

比如获取去掉后缀名的前缀

ls -al | cut -d “.” -f1

比如获取后缀名

ls -al | cut -d “.” -f2

here string可以看成是here document的一种定制形式. 除了COMMAND <<<$WORD, 就什么都没有了, de>$WORDde>将被扩展并且被送入de>COMMANDde>的stdin中.

1 String="This is a string of words."

2

3 read -r -a Words <<< "$String"

4 # "read"命令的-a选项

5 #+ 将会把结果值按顺序的分配给数组中的每一项.

6

7 echo "First word in String is: ${Words[0]}" # This

8 echo "Second word in String is: ${Words[1]}" # is

9 echo "Third word in String is: ${Words[2]}" # a

10 echo "Fourth word in String is: ${Words[3]}" # string

11 echo "Fifth word in String is: ${Words[4]}" # of

12 echo "Sixth word in String is: ${Words[5]}" # words.

13 echo "Seventh word in String is: ${Words[6]}" # (null)

14 # $String的结尾.

15

16 # 感谢, Francisco Lobo的这个建议.
例子 17-13. 在一个文件的开头添加文本

1 #!/bin/bash

2 # prepend.sh: 在文件的开头添加文本.

3 #

4 # Kenny Stauffer所捐助的脚本例子,

5 #+ 本文作者对这个脚本进行了少量修改.

6

7

8 E_NOSUCHFILE=65

9

10 read -p "File: " file # 'read'命令的-p参数用来显示提示符.

11 if [ ! -e "$file" ]

12 then # 如果这个文件不存在, 那就进来.

13 echo "File $file not found."

14 exit $E_NOSUCHFILE

15 fi

16

17 read -p "Title: " title

18 cat - $file <<<$title > $file.new

19

20 echo "Modified file is $file.new"

21

22 exit 0

23

24 # 下边是'man bash'中的一段:

25 # Here String

26 # here document的一种变形,形式如下:

27 #

28 # <<<word

29 #

30 # word被扩展并且被提供到command的标准输入中.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: