Chinaunix首页 | 论坛 | 博客
  • 博客访问: 612917
  • 博文数量: 486
  • 博客积分: 10125
  • 博客等级: 上将
  • 技术积分: 5842
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-27 18:34
文章分类

全部博文(486)

文章存档

2011年(52)

2010年(107)

2009年(289)

2008年(38)

我的朋友

分类: LINUX

2010-09-06 20:48:35



bash shell字符串截取



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."

3 read -r -a Words <<< "$String"
4 # "read"命令的-a选项
5 #+ 将会把结果值按顺序的分配给数组中的每一项.

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 #+ 本文作者对这个脚本进行了少量修改.


8 E_NOSUCHFILE=65

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 # << 29 #
30 # word被扩展并且被提供到command的标准输入中.

阅读(857) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~