command-line 学习:检阅文件
使用的电脑为 mac 。
参考:Learn Enough Command Line to Be Dangerous
下载文件
用 which 命令可以查看命令行是否支持 curl,
$ which curl
/usr/bin/curl
如果输出结果是空的,说明不支持,得安装。可以自行 google 关键词 install curl 进行安装。
curl 安装好,可以下载文件了。
$ curl -OL cdn.learnenough.com/sonnets.txt
$ ls -rtl
$ !! # 可以出来最近一次使用的命令
$ !curl # 可以出来最近一次使用 curl 开头的命令
还有一个小技巧,可以使用 ctrl + r,这个可以进行搜索,输入 curl ,便可以查询以 curl 开头的命令。
$ 按住 ctrl 和 R
(reverse-i-search)`': curl
head tail
$ head sonnets.txt # 查看 sonnets.txt 文件的前 10 行
$ tail sonnets.txt # 查看 sonnets.txt 文件的后 10 行
$ wc sonnets.txt # 查看 sonnets.txt 文件有多少行,多少字,多少字节 2620 17670 95635 sonnets.txt
# 把 sonnets.txt 的 head 部分放入 sonnets_head.txt,并统计 sonnets_head.txt 中有多少行,多少字,和多少字节
$ head sonnets.txt > sonnets_head.txt
$ wc sonnets_head.txt 10 46 294 sonnets_head.txt
# 用一行命令也可以搞定
$ head sonnets.txt | wc 10 46 294Â
less more
$ less sonnets.txt
这个可以给文件一个导航,然后你可以通过 ↑ ↓,空格键去翻页。按 ctrl + f 可以一下到下个目录,ctrl + b 可以到上一个目录。输入 q 退出。
还可以 输入 /rose 来搜索 rose,可以按 n 去到下一个匹配的地方, N 去到上一个匹配的地方。
还有一个 G 去到文件的结尾,1G 去到文件的开头。
less 中的命令,和 man 中的类似,所以会了 less ,man 中的也可以很好的使用了。
| Command | Description | Example |
|---|---|---|
| up & down arrow keys | Move up or down one line | |
| spacebar | Move forward one page | |
| ctrl + f | Move forward one page | |
| ctrl + b | Move back one page | |
| G | Move to end of file | |
| 1G | Move to beginning of file | |
| /<string> | Search file for string | /rose |
| n | Move to next search result | |
| N | Move to previous search result | |
| q | Quit less |
grep
$ grep rose sonnets.txt # 找出所有存在 rose 的地方
$ grep rose sonnets.txt | wc # 统计出现 rose 的行数 字数 字节数(大写的 Rose 不能被统计到,grep 大小写敏感)
10 82 419
$ grep -i rose sonnets.txt | wc # 不计大小写统计 12 96 508
ps 是 process status 的缩写。
ps -aux
$ ps aux
$ ps aux | grep spring # 查看 spring 进程
ubuntu 12241 0.3 0.5 589960 178416 ? Ssl Sep20 1:46
spring app | sample_app | started 7 hours ago
$ kill -15 12241 # 杀死 12241 进程
$ pkill -15 -f spring # 杀死所有的 spring 进程
$ top # 可查看所有的进程
| Command | Description | Example |
|---|---|---|
| curl | Interact with URLs | $ curl -O example.com |
| which | Locate a program on the path | $ which curl |
| head <file> | Display first part of file | $ head foo |
| tail <file> | Display last part of file | $ tail bar |
| wc <file> | Count lines, words, bytes | $ wc foo |
| cmd1 | cmd2 | Pipe cmd1 to cmd2 | $ head foo | wc |
| ping <url> | Ping a server URL | $ ping google.com |
| less <file> | View file contents interactively | $ less foo |
| grep <string> <file> | Find string in file | $ grep foo bar.txt |
| grep -i <string> <file> | Find case-insensitively | $ grep -i foo bar.txt |
| ps | Show processes | $ ps aux |
| top | Show processes (sorted) | $ top |
| kill -<level> <pid> | Kill a process | $ kill -15 24601 |
| pkill -<level> -f <name> | Kill matching processes | $ pkill -15 -f spring |