shell编程-字符截取命令

1、cut字段提取命令

在这里插入图片描述

[root@localhost sh]# cat student.txt 
ID	Name	gender	Mark
1	dd	M	90
2	drt	M	98
3	go	M	87
[root@localhost sh]# cut -f 2 student.txt 
Name
dd
drt
go
[root@localhost sh]# 
[root@localhost sh]# cut -f 2,4 student.txt 
Name	Mark
dd	90
drt	98
go	87
[root@localhost sh]# 
[root@localhost sh]# cut -d ":" -f 1,3 /etc/passwd
[root@localhost sh]# cat /etc/passwd | grep /bin/bash | grep -v root | cut -d ":" -f 1

2、printf格式化输出命令

在这里插入图片描述
在这里插入图片描述

[root@localhost sh]# printf %s 1 2 3 4 5 6
123456[root@localhost sh]# printf %s %s %s 1 2 3 4 5 6
%s%s123456[root@localhost sh]# printf '%s %s %s' 1 2 3 4 5 6
1 2 34 5 6[root@localhost sh]# printf '%s %s %s\n' 1 2 3 4 5 6
1 2 3
4 5 6
[root@localhost sh]# 

3、awk命令

在这里插入图片描述

[root@localhost sh]# awk '{printf $2 "\t" $3 "\n"}' student.txt 
[root@localhost sh]# df -h | awk '{print $1 "\t" $3}'
[root@localhost sh]# df -h | grep sda5 | awk '{print $5}' | cut -d "%" -f 1

[root@localhost sh]# awk 'BEGIN{printf "this is a transcript\n"} {printf $2 "\t" $3"\n"}' student.txt 
[root@localhost sh]# cat /etc/passwd | grep "/bin/bash" | awk 'BEGIN {FS=":"} {printf $1 "\t" $3 "\n"}'
[root@localhost sh]# awk 'END{printf "the end \n"} {printf $2 "\t" $4 "\n"}' student.txt 
[root@localhost sh]# cat student.txt | grep -v Name | awk '$4>=80 {printf $2 "\n"}'

4、sed命令

在这里插入图片描述
命令格式
在这里插入图片描述
动作
在这里插入图片描述
#查看文件第二行

[root@localhost sh]# sed -n '2p' student.txt 
1	dd	M	90
[root@localhost sh]# df -h | sed -n '2p'
/dev/sda5        16G  4.0G   11G  28% /

#删除第一到第三行的数据,但不修改文件本身

[root@localhost sh]# sed '1,3d' student.txt 
3	go	M	87
[root@localhost sh]# cat student.txt 
ID	Name	gender	Mark
1	dd	M	90
2	drt	M	98
3	go	M	87
[root@localhost sh]# 

在第二行后追加hello

[root@localhost sh]# sed '2a hello' student.txt 
ID	Name	gender	Mark
1	dd	M	90
hello
2	drt	M	98
3	go	M	87

在第二行前插入两行数据

[root@localhost sh]# sed '2i hello \
> woeld' student.txt
ID	Name	gender	Mark
hello 
woeld
1	dd	M	90
2	drt	M	98
3	go	M	87
[root@localhost sh]# 

sed字符串替换
#sed ‘s/旧字串/新字串/g’ 文件名

在第三行中把98替换成89
[root@localhost sh]# sed '3s/98/89/g' student.txt 
ID	Name	gender	Mark
1	dd	M	90
2	drt	M	89
3	go	M	87

sed操作的数据直接写入文件

[root@localhost sh]# sed -i '3s/98/89/g' student.txt 
[root@localhost sh]# cat student.txt 
ID	Name	gender	Mark
1	dd	M	90
2	drt	M	89
3	go	M	87
[root@localhost sh]# 

同时把go和dd替换为空

[root@localhost sh]# sed -e 's/go//;s/dd//' student.txt 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值