linux命令-字符串操作

 

【1】tr

替换连续重复字符

[root@wxl-1 ~]# echo aa1aa | tr -s a
a1a
[root@wxl-1 ~]# echo aa1aa | tr -s a b
b1b

删除字符

[root@wxl-1 ~]# echo aa1aa | tr -d 1
aaaa
[root@wxl-1 ~]# echo aa1aa | tr -d a
1

替换字符

[root@wxl-1 ~]# echo aa1aa | tr -t a b
bb1bb
[root@wxl-1 ~]# echo aa1aa | tr a b  #缺省的就是-t
bb1bb

字符补集替换(替换没有指定的字符)

[root@wxl-1 ~]# echo aa1aa | tr -c "1\n"  b  #1和换行以外的字符全部替换成b
bb1bb
[root@wxl-1 ~]# echo aa1aa | tr -c "a\n"  b  #a和换行以外的字符全部替换成b
aabaa

 

【2】expr

match 匹配字符串

格式:expr match $string substring

描述:在string字符串中匹配substring字符串(substring字符串可以是正则表达式),然后返回匹配到的substring字符串的长度,若找不到则返回0

举例:

[root@wxl-1 ~]# expr match "wxl12221121" .*121
11
 

substr 截取字符串

格式:expr substr stringstringposition $length

描述:从substr 的stringstringposition位置截取length长度 (坐标是从1开始计算)

举例:

[root@wxl-1 ~]# expr substr "wxlxxxwxl" 2 2
xl
 

附加:{string:position}和{string:position:length}也可以实现类似的功能,不过计算下标是从0开始的

[root@wxl-1 ~]# aa=wxlwxl
[root@wxl-1 ~]# echo ${aa:2}
lwxl
[root@wxl-1 ~]# echo ${aa:2:2}
lw
 

index 定位字符

格式:expr index string substring

描述:在字符串stringsubstring索引命令功能在字符串string上找出substring中字符第一次出现的位置,若找不到则expr index返回0,注意它匹配的是字符而非字符串

举例:

[root@wxl-1 ~]# expr index wxwwwad a
6
 

length 计算长度

格式:expr length string

描述:得到string的长度

举例:

[root@wxl-1 ~]# cc=asddsa
[root@wxl-1 ~]# expr length $cc
6

 

【3】awk

见我另一个文章:https://blog.csdn.net/github_30641423/article/details/107094812

 

【4】其他常用字符串操作

查询子串,返回包含子串的行

grep "hello" test.txt #grep是最适合的

#awk也可以完成
awk '/hello/{ printf("%s:%d:%s\n",FILENAME, FNR, $0)}' test.txt

#sed也可以完成
sed -n -e '/consists of/=;/consists of/p' test.txt

 

字串内容替换

$ var="get the length of me"
【1】{}实现
$ echo ${var/ /_}        #把第一个空格替换成下划线
get_the length of me
$ echo ${var// /_}       #把所有空格都替换成下划线
get_the_length_of_me

【2】awk实现
$ echo $var | awk '{sub(" ", "_", $0); printf("%s\n", $0);}'
get_the length of me
$ echo $var | awk '{gsub(" ", "_", $0); printf("%s\n", $0);}'
get_the_length_of_me

【3】sed实现(sed最适合替换)
$ echo $var | sed -e 's/ /_/'    #s <= substitude
get_the length of me
$ echo $var | sed -e 's/ /_/g'  
get_the_length_of_me

删除子串

var="get the length of me"

#删除所有空格

#【1】用 {}
$ echo ${var// /}
getthelengthofme

#【2】用 awk
$ echo $var | awk '{gsub(" ","",$0); printf("%s\n", $0);}'

#【3】用 sed
$ echo $var | sed 's/ //g'
getthelengthofme

#【4】用tr
$ echo $var | tr -d " "
getthelengthofme

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙叔运维

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值