bashshell字符串的截取
shell字符串的截取的问题:
⼀、Linux shell 截取字符变量的前8位,有⽅法如下:
⼆、按指定的字符串截取
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
shell 字符串长度⽐如获取后缀名
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 > $w
19
20 echo "Modified file is $w"
21
22 exit 0
23
24 # 下边是'man bash'中的⼀段:
25 # Here String
26 # here document的⼀种变形,形式如下:
27 #
28 # <<<word
29 #
30 # word被扩展并且被提供到command的标准输⼊中.
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论