目录
知识概览
seq
seq可以生成指定开始和指定结束的序列:
#产生指定范围的序列:
[root@localhost shell]# seq 23 26
23
24
25
26
与此同时,它还可以指定步长:
[root@localhost shell]# seq 20 +2 28
20
22
24
26
28
在shell脚本的循环中,用seq生成循环数是最好的选择。
xargs
传参命令,将前面命令的输出作为后面命令的参数使用。
#这里,我们生成了1-5的序列,通过管道符号的连接,将序列变成5个文件夹名
[root@localhost circle]# seq 5 |xargs mkdir
[root@localhost circle]# ls
1 3 5 for.sh name.txt while2.sh while.sh
2 4 a_name.txt grade.txt QandA.sh while3.sh
#这里跟上面一样,又把这五个文件夹删除了
[root@localhost circle]# seq 5 |xargs rm -rf
[root@localhost circle]# ls
a_name.txt for.sh grade.txt name.txt QandA.sh while2.sh while3.sh while.sh
tr
1、tr有转换功能:
下面的例子,将1、2、3分别对应转换为a、b、c三个字符并输出。
[root@localhost circle]# echo 112233
112233
[root@localhost circle]# echo 112233| tr 123 abc
aabbcc
2、删除功能:
tr能删除获取的文本的指定内容,获得我们需要的专属内容,下面的例子所示,抓取文本的一行之后,使用tr删除了指定字符“%”:
#df命令的功能是用来检查文件系统的磁盘空间占用情况,然后获取以“/”结尾的行
[root@localhost circle]# df -Th |grep "/$"
/dev/mapper/centos-root xfs 17G 2.5G 15G 15% /
#拿到这一行的第六个字段
[root@localhost circle]# df -Th |grep "/$" |awk '{print $6}'
15%
#使用tr删除了%符号
[root@localhost circle]# df -Th |grep "/$" |awk '{print $6}' |tr -d "%"
15
tr后面接 _-d 可以删除指定内容;
tr后面接 -s 可以压缩连续的字符串内容。
#这里tr命令将字符串中的b字符全部删除了
[root@localhost circle]# echo "yuhbengbbxing" |tr -d "b"
yuhengxing
#这里tr删除了重复出现的字符,实现了字符串压缩去重的效果
[root@localhost circle]# echo "1122233333434443322" |tr -s "1234"
12343432
cut
截取文件中的字符串和列。
1、截取字符串:
#截取字符串,截取第一个到第十个字符:
[root@localhost circle]# echo "yuhengxingbbbbbbb8**" |cut -c 1-10
yuhengxing
2、截取列:
#截取列,使用-f截取第二列:
[root@localhost circle]# cat grade.txt
name chinese math english
cali 80 90 8
tom 90 20 99
lucy 30 70 75
yhx 100 100 10
[root@localhost circle]# cat grade.txt |cut -f 2
chinese
80
90
30
100
cut ----截取字符串--> -c
----截取字段 --> -f
----截取字段 --> -d 指定分隔符
cut用来截取字符串更合适,awk适合截取字段,因为awk既可以用tab分割,也可以把空格当作分割。
sort
排序,默认根据第一个字母的ASCII码大小进行升序排列。
sort可以排序文件内容:
[root@localhost shell]# cat uniq.txt
yhx
yuhengxing
yhx
yuhengxing
kkkkk
yhx
yuhengxing
yhx
yuhengxing
kkkkk
[root@localhost shell]# cat uniq.txt |sort
kkkkk
kkkkk
yhx
yhx
yhx
yhx
yuhengxing
yuhengxing
yuhengxing
yuhengxing
-n --- 可以让字符串识别成数值
-r --- 可以降序排列
-k --- 可以指定排序的列
-t --- 可以指定分隔符
#根据第二列排序:
[root@localhost circle]# cat grade.txt |sort -k 2 -n
name chinese math english
lucy 30 70 75
cali 80 90 8
tom 90 20 99
yhx 100 100 10
uniq
6、uniq:唯一,可以去重
-c --- 统计重复次数
-u --- 打印不重复的行
-d -- 打印重复的行
#对于刚刚上面排序的文件内容,使用uniq可以去重:
[root@localhost shell]# cat uniq.txt |sort|uniq
kkkkk
yhx
yuhengxing
#-c可以统计重复出现的次数:kkkkk出现两次,yhx出现4次,yuhengxing出现4次:
[root@localhost shell]# cat uniq.txt |sort|uniq -c
2 kkkkk
4 yhx
4 yuhengxing
以上就是文件处理的相关命令,如有问题欢迎评论区留言或私信询问。上述出现的命令在以前的合集中基本全部提到过,并且有详细的使用和解析。