本文详细介绍bash中字符串的处理
1.得到字符串长度
方法一:
$echo ${#variable}
code:
PHP 代码:zhyfly: ~$ x="this is a test"方法二:
zhyfly: ~$ echo ${#x}
14
$expr length "$variable"
code:
PHP 代码:zhyfly: ~$ x="this is a test"方法三:
zhyfly: ~$ expr length "$x"
14
$expr "$variable" : ".*"
code:
PHP 代码:zhyfly: ~$ x="this is a test"2.查找字符串子串位置
zhyfly: ~$ expr "$x" : ".*"
14
方法:
$expr index "$variable" "substring"
code:
PHP 代码:zhyfly: ~$ x="this is a test"(ps:如果出现重复,好象只能查到第一个,第二个,第三个,...,怎么查到呢???)
zhyfly: ~$ expr index "$x" "is"
3
zhyfly: ~$ expr index "$x" "t"
1
3.得到字符串子字符串
方法一:
$echo ${variable:position:length}
code:
PHP 代码:zhyfly: ~$ x="this is a test"方法二:
zhyfly: ~$ echo ${x:1:5}
his i
$expr substr "$variable" startposition length
code:
PHP 代码:zhyfly: ~$ x="this is a test"(ps:注意方法一和方法二中位置的区别!)
zhyfly: ~$ expr substr "$x" 1 5
this
4.匹配正则表达式之匹配长度
方法:
$expr match "$x" "string"
code:
PHP 代码:zhyfly: ~$ x="this is a test"5.字符串的掐头去尾
zhyfly: ~$ expr match "$x" "his"
0
zhyfly: ~$ expr match "$x" "this"
4
zhyfly: ~$ expr match "$x" "."
1
方法:
$echo ${variable#startletter*endletter} # #表示掐头,因为键盘上#在$前面,一个表示最小匹配
$echo ${variable##tartletter*endletter} 两个表示最大匹配
$echo ${variable%startletter*endletter} # %表示去尾,因为键盘上%在$后面,一个表示最小匹配
$echo ${variable%%startletter*endletter} 两个表示最大匹配
code:
PHP 代码:zhyfly: ~$ x="this is a test"
zhyfly: ~$ echo ${x#t}
his is a test
zhyfly: ~$ echo ${x#t*h}
is is a test
zhyfly: ~$ echo ${x#t*s}
is a test
zhyfly: ~$ echo ${x##t*s}
t
zhyfly: ~$ echo ${x%t}
this is a tes
zhyfly: ~$ echo ${x%s*t}
this is a te
zhyfly: ~$ echo ${x%e*t}
this is a t
zhyfly: ~$ echo ${x%%i*t}
th
6.字符(串)的替换
方法:
$echo ${variable/oldletter/newletter} #替换一个
$echo ${variable//oldletter/newletter} #替换所有
code:
PHP 代码:zhyfly: ~$ x="this is a test"
zhyfly: ~$ echo ${x/i/m}
thms is a test
zhyfly: ~$ echo ${x//i/m}
thms ms a tes
责编:豆豆技术应用
- Linux/Unix新闻
- Linux/Unix入门
- Linux/Unix命令
- Linux/Unix安装
- Linux/Unix编程
- Linux/Unix管理
- Linux/Unix桌面
- Linux/Unix内核
- Linux/Unix软件
- Linux/Unix发行版
- redhat/Fedora
- Ubuntu Linux
- IBM AIX
- FreeBSD
- Solaris
- NetBSD
- SCO Unix
- find基本用法
- ldd命令原理及用法例子
- su和sudo命令的区别与使用技巧
- Linux操作系统下的dd命令技巧
- 关于Top命令的参数详解
- 关于Tar命令的使用
- SSH实用技巧及常用命令使用
- Linux后台执行命令
- VI命令使用技巧集锦
- Vmstat命令列出的属性详解
- 如何查看及修改文件读写权限
- 最大可存储的单文件容量
- ext2/ext3文件系统介绍
- 常用压缩格式的压缩解压方法
- Linux系统的引导过程详细解析
- Configure参数解释说明
- Linux下硬盘和分区的命名方法
- 硬链接与软链接的区别
- 权限和所有权模型
- 存储设备的两种表示方法