Shell—文件内容操作

读取文件的每一行内容并输出

#!/bin/bash

# 方法1
while read line
do
    echo $line
done < a.txt


# 方法2
cat a.txt | while read line
do
    echo $line
done

# 方法3
# for line in `cat  a.txt`
for line in $(cat a.txt)
do
    echo $line
done

文件内容排序工具 sort 和 uniq

sort:sort是一个以行为单位对文件内容进行排序的工具,也可以根据不同的数据类型来排序。

用法:sort [选项] 参数

  • -n:按照数字进行排序
  • -r:反向排序
  • -u:等同于uniq,表示相同的数据仅显示一行
  • -f:忽略大小写      -b:忽略每行前面的空格      -M:按照月份进行排序
  • -t:指定分隔符,默认使用Tab键分隔     -o <输出文件>:将排序后的结果转存至指定文件   -k:指定排序区域
[root@localhost ~]# sort /etc/passwd
[root@localhost ~]# sort -r /etc/passwd

uniq:去除重复行,并统计每行出现的次数(相邻行)。uniq工具通常与sort命令结合使用,用于报告或者忽略文件中的重复行。

用法:uniq [选项] 参数

  • -c:进行计数
  • -d:仅显示重复行(这里的重复行,仅限相邻行重复。如果有两行重复但是不相邻,则不满足)
  • -u:仅显示出现一次的行
[root@localhost ~]# uniq -c test.txt
[root@localhost ~]# uniq -u test.txt
[root@localhost ~]# sort -n test.txt | uniq -c  # 删除test.txt文件中重复行,并统计该行重复次数

[root@localhost ~]# sort -n test.txt | awk '{if($0!=line)print; line=$0}'
[root@localhost ~]# sort -n test.txt | sed '$!N; /^\(.*\)\n\1$/!P; D'

统计文件的行数、字数、字节数, 并将统计结果显示输出

[root@localhost ~]# wc -l /etc/passwd         # 统计文件的行数(里面内容的行数)
[root@localhost ~]# wc -c /etc/passwd         # 统计文件的字节数
[root@localhost ~]# wc -m /etc/passwd         # 统计文件的字符数
[root@localhost ~]# wc -w /etc/passwd         # 统计单词出现次数
[root@localhost ~]# wc - lcw file1 file2 
[root@localhost ~]# ls -l | wc -l             # 用来统计当前目录下的文件数

  

猜你喜欢

转载自blog.csdn.net/qq_45533841/article/details/112470907
今日推荐