linux命令行【十】文件内容操作

  • cat file1
    查看文件,从第一行开始

  • tac file1
    查看文件,从最后一行开始

  • more file1
    查看文件内容,只能往后看文件

  • less file1
    less 与 more 类似,但使用 less 可以随意浏览文件,而 more 仅能向前移动,却不能向后移动,而且 less 在查看之前不会加载整个文件。

  • head -2 file1
    查看文件前两行

  • tail -2 file1
    查看文件后两行

  • tail -f /var/log/messages
    实时查看文件信息

  • cat file_test | [operation: sed, grep, awk, grep, etc] > result.txt
    检索文件内容,并覆盖 result.txt 内容

  • cat file_originale | [operazione: sed, grep, awk, grep, etc] >> result.txt
    检索文件内容,并追加 result.txt 内容

  • grep Aug /var/log/messages
    搜索 '/var/log/messages' 的关键词 Aug

  • grep ^Aug /var/log/messages
    搜索以 Aug 开头的关键词

  • grep [0-9] /var/log/messages
    搜索 '/var/log/messages' 包含数字的所有行

  • grep Aug -R /var/log/*
    在目录 '/var/log' 搜索关键词 Aug

  • sed 's/stringa1/stringa2/g' example.txt
    在 example.txt 中搜索 string1 并用 string2 替换该关键词

  • sed '/^$/d' example.txt
    删除所有空白行

  • sed '/ *#/d; /^ *$/d' example.txt
    删除注释和空白行

  • echo 'esempio' | tr '[:lower:]' '[:upper:]'
    使用 tr 命令把小写转换成大写

  • sed -e '1d' result.txt
    删除第一行

  • sed -n '/stringa1/p'
    只查看包含有 stringa1 的行

  • sed -e 's/ *$//' example.txt
    每行末尾删除空白字符

  • sed -e 's/stringa1//g' example.txt
    查询字符串 stringa1 并用空白字符替换

  • sed -n '1,5p;5q' example.txt
    查看1-5行

  • sed -n '5p;5q' example.txt
    查看第5行

  • sed -e 's/00*/0/g' example.txt
    替换多个0为一个0

  • cat -n file1
    按照行号查看一个文件

  • cat example.txt | awk 'NR%2==1'
    只查看奇数行

  • echo a b c | awk '{print $1}'
    查看行的第一列

  • echo a b c | awk '{print \(1,\)3}'
    查看行的第一列和第三列

  • paste file1 file2
    合并两个文件,把每个文件以列对列的方式,一列列地加以合并

  • paste -d '+' file1 file2
    用指定的间隔字符取代跳格字符

  • sort file1 file2
    两个文件内容排序

  • sort file1 file2 | uniq
    根据两个文件内容排序,忽略重复的行

  • sort file1 file2 | uniq -u
    排序两个文件内容,查看不一样的行

  • sort file1 file2 | uniq -d
    排序两个文件内容,查看重复的行

  • comm -1 file1 file2
    比较两个文件内容,发现与文件 file1 不同的行

  • comm -2 file1 file2
    比较两个文件内容,发现与文件 file2 不同的行

  • comm -3 file1 file2
    比较两个文件内容,发现两个文件不同的行