Linux学习——cat, less, grep, sed

cat
cat可以用来查看文件内容,-n可以显示行数

cat -n data4.txt

[root@localhost Documents]# cat -n data4.txt
1 This is a test of the trial script.
2 This is the second test of the trial script.
3 This is a test of the test script.

less
less的用法和more的用法类似,也是用来查看文件内容,不过less可以使用 /string的命令模式,进行查找,可以用空格向下翻页,用u向上翻半页。

-N 会显示行数,-m会想more一样显示百分比

[root@localhost Documents]# less -Nm process.txt
20 root 22 0.0 0.0 0 0 ? S< 15:04 0:00 [md]
21 root 23 0.0 0.0 0 0 ? S< 15:04 0:00 [edac-poller]
22 root 24 0.0 0.0 0 0 ? S< 15:04 0:00 [watchdogd]
23 root 30 0.1 0.0 0 0 ? S 15:04 0:28 [kswapd0]
24 root 31 0.0 0.0 0 0 ? SN 15:04 0:00 [ksmd]
25 root 32 0.0 0.0 0 0 ? SN 15:04 0:01 [khugepaged]
26 root 33 0.0 0.0 0 0 ? S< 15:04 0:00 [crypto]
27 root 41 0.0 0.0 0 0 ? S< 15:04 0:00 [kthrotld]
28 root 43 0.0 0.0 0 0 ? S< 15:04 0:00 [kmpath_rdacd]
29 root 44 0.0 0.0 0 0 ? R< 15:04 0:00 [kaluad]
process.txt 11%

底部输入/R,就会找到所有的R

27 root 41 0.0 0.0 0 0 ? S< 15:04 0:00 [kthrotld]
28 root 43 0.0 0.0 0 0 ? S< 15:04 0:00 [kmpath_rdacd]
29 root 44 0.0 0.0 0 0 ? R< 15:04 0:00 [kaluad]
/R

日志查看例子:
我们有时需要查看/var/log/messages中的日志信息,其中包含了系统的各种日志,包括各种警告或者报错,会记录到这个日志文件里,而这个文件是有上万行的,我们没办法直接一页页的查看我们需要的内容。这时用less就很方便。

查看error

less -Nm /var/log/messages

/error

键盘中键入:

n 下一个
N 上一个

u     上半页
space 下一页

或者也可以使用以下命令,查看最后30行的日志信息

tail -30 /var/log/messages

同时,tail命令还可以监控实时的内容变化情况,比如系统运行程序,日志内容也一直在更新,那么我们可以用tail -f 就可以实时看到,不断被新加入日志的内容。

tail -f /var/log/messages

grep
这个是linux三剑客之一

  • 用来正则匹配查找文件的内容
  • 每次只读取一行
  • 显示匹配到内容的所在行
grep pattern file

[root@localhost Documents]# grep -n R+ process.txt
216:root 56821 0.0 0.1 155372 1864 pts/0 R+ 21:25 0:00 ps aux
221:root 56821 0.0 0.1 155372 1864 pts/0 R+ 21:26 0:00 ps aux

-n 会显示所在的行号
要注意:

  • 这里边的正则,只有^, $, . 有用,其他的* { } 等之类的都当成普通字符,如果当成正则匹配的字符,需要加上\
  • 通配符 * 一般用来匹配文件名

sed
Linux三剑客之一

  • 用来替换/删除文件内容的字符串/行
  • 是以流的方式更改,不会更改原文件的内容
  • 也可以正则匹配
sed 's/pattern/replacement/flags' file

[root@localhost Documents]# sed ‘s/test/trial/g’ data4.txt
This is a trial of the trial script.
This is the second trial of the trial script.
This is a trial of the trial script.

  • s表示替换
  • pattern匹配的内容
  • replacement替换成的内容
  • g所有匹配到的都替换
sed 'd' file

删除第三行

[root@localhost Documents]# sed ‘3d’ data1.txt
This is line number 1.
This is line number 2.
This is line number 4.
This is a test of the trial script.
This is the second test of the trial script.
This is a test of the test script.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值