linux 常用文本操作

cat 连接文件,打印到标准输出设备上

语法介绍

cat [OPTION]... [FILE]...
-A --show-all 等价于-vET
-b 显示编号去除空行
-n 显示编号包括空行
-E 显示行结束符
-s 连续的多行空白,显示一行
-T 显示tab
-v 使用 ^ 和 M- 符号,除了 LFD 和 TAB 之外。

使用场景:

显示行号

[root@localhost ~]# cat -n anaconda-ks.cfg

连接查看

[root@localhost ~]# cat -n anaconda-ks.cfg /etc/hosts

合并文件

[root@localhost ~]# cat t1 t2 > t3

重定向文本输入

[root@localhost ~]# cat << EOF
hello world
EOF
hello world

重定向文件输入

[root@localhost ~]# cat < anaconda-ks.cfg


more

按百分比显示文件,有过滤,搜索功能,对于大文件比cat更方便阅读

参数:

-num 一次显示的行数
-d 提示使用者,在画面下方显示 [Press space to continue, 'q' to quit.] ,如果使用者按错键,则会显示 [Press 'h' for instructions.] 而不是 '哔' 声
-l 取消遇见特殊字元 ^L(送纸字元)时会暂停的功能
-f 计算行数时,以实际上的行数,而非自动换行过后的行数(有些单行字数太长的会被扩展为两行或两行以上)
-p 不以卷动的方式显示每一页,而是先清除萤幕后再显示内容
-c 跟 -p 相似,不同的是先显示内容再清除其他旧资料
-s 当遇到有连续两行以上的空白行,就代换为一行的空白行
-u 不显示下引号 (根据环境变数 TERM 指定的 terminal 而有所不同)
+/pattern 在每个文档显示前搜寻该字串(pattern),然后从该字串之后开始显示
+num 从第 num 行开始显示
fileNames 欲显示内容的文档,可为复数个数

操作命令:

Enter 向下n行,需要定义。默认为1行
Ctrl+F 向下滚动一屏
空格键 向下滚动一屏
Ctrl+B 返回上一屏
= 输出当前行的行号
:f 输出文件名和当前行的行号
V 调用vi编辑器
!命令 调用Shell,并执行命令
/keyword 搜索关键字
q 退出more

常用操作:

[root@localhost ~]# more -s -20 anaconda-ks.cfg


less

比more更加灵活,鼠标可以往前往后滚动,随意浏览,还是懒加载,参数用法跟more类似

常用操作:

[root@localhost ~]# less -s -20 anaconda-ks.cfg


head

查看文件前几行

[root@localhost ~]# head -2 anaconda-ks.cfg


tail

查看文件末尾几行,还有监控文件功能

参数:

-n 显示行数
-f 监控文件

常用操作

[root@localhost ~]# tail -2 anaconda-ks.cfg
[root@localhost ~]# tail -f anaconda-ks.cfg


基于python实现 tail查看文件末尾几行功能

def read_last_lines(filename,lastlines=1):

    f = open(filename, 'rb')
    first_line_data,first_tell = f.readline(),f.tell()
    f.seek(0)
    seek = 0

    #第一层循环判断是否为空文件
    for i in f:
        while True:
            f.seek(seek,2)
            current_tell = f.tell()
            seek -= 1
            data = f.readlines()

            if(first_tell == current_tell and not data):
                f.close()
                return  '1',[first_line_data]
            elif(first_tell == current_tell and data):
                if(len(data)<lastlines):
                    data.insert(0,first_line_data)
                f.close()
                return  '2',data
            else:
                if(lastlines != 1):
                    if(len(data) == lastlines):
                        return  '3',data
                else:
                    if (len(data) == 1):
                        if (first_tell == f.tell()):
                            f.close()
                            return '4', data[-1:]

                    if (len(data) > 1):
                        f.close()
                        return  '5', data[-1:]

data = read_last_lines('test2.txt',lastlines=10)
print(data)

未完待续....

猜你喜欢

转载自blog.51cto.com/marvin89/2104946
今日推荐