LINUX
Linux 终端命令第 1 部分:切换目录、查找和阅读文件
ls、pwd、cd、find、grep、cat、less 和 wc。重新审视 2024 年 1 月的指南,其中的示例输出和正文对不上。这个版本使用的是真实输出。
2024 年 1 月,我发表了 Linux 终端命令指南的第一部分,介绍如何定位当前位置、查找文件以及查看文件内容。
重读之后,我发现示例输出和讲解对不上:ls -a 的输出里用省略号代替了 ..;grep 只显示了一行,正文却说”两行”;
用户目录被写成了 /user/user_name,其实应该是 /home/user_name。
为了这个版本,我建了一个示例文件夹,并在里面逐个运行了这些命令。下面的输出都是终端实际返回的结果。
示例文件是葡萄牙语的,因为这份指南最初是用葡萄牙语写的;这一点在后面的 wc 部分会用到。
第 2 部分 接着介绍创建、移动和删除文件的命令。
示例文件夹就是用户目录,里面有三个文件夹、两个隐藏文件,文件夹里还有几个文件。其中 Documentos/notas.txt 有四行:
Linux é uma família de sistemas operacionais de código aberto.
Ele usa o kernel criado por Linus Torvalds em 1991.
Eu uso Linux para programar.
É rápido e dá para configurar quase tudo.
我在哪里:pwd
$ pwd
/home/ana
pwd 显示当前目录。打开终端时,通常位于用户目录,即 /home/<用户名>。
这里有什么:ls
$ ls
Documentos Downloads Musica
加上 -a,隐藏的项目也会显示出来,也就是以点开头的那些:
$ ls -a
. .. .bashrc .profile Documentos Downloads Musica
. 表示当前目录本身,.. 表示上一级目录。.bashrc 和 .profile 是 shell 的配置文件。
要查看权限、所有者、大小和日期等详细信息,使用 ls -l。我专门写过一篇介绍 ls 选项的文章:
ls 命令。
切换位置:cd
$ cd Documentos # 进入 Documentos
$ cd .. # 返回上一级
$ cd # 不带参数,回到用户目录
$ cd - # 回到上一个所在的目录
~ 是用户目录的简写:cd ~/Downloads 在任何位置都能用。
查找文件:find
不加筛选条件时,find 会递归列出路径下的所有内容:
$ find .
.
./.bashrc
./.profile
./Documentos
./Documentos/notas.txt
./Documentos/relatorio.pdf
./Downloads
./Downloads/pacote.zip
./Musica
加上 -name,就按名称筛选。引号很重要:没有引号,shell 会在 find 收到模式之前先尝试展开 *。
$ find . -name "*.txt"
./Documentos/notas.txt
两个有用的筛选条件:-type f 只返回文件,-type d 只返回目录。要在名称中忽略大小写,使用 -iname。
在文件中查找:grep
grep 会显示包含所查找文本的行:
$ grep "Linux" Documentos/notas.txt
Linux é uma família de sistemas operacionais de código aberto.
Eu uso Linux para programar.
四行中有两行包含 “Linux” 这个词。几个有用的选项:
$ grep -n -i "linux" Documentos/notas.txt # -n 显示行号,-i 忽略大小写
1:Linux é uma família de sistemas operacionais de código aberto.
3:Eu uso Linux para programar.
$ grep -c "Linux" Documentos/notas.txt # 只统计行数
2
$ grep -r "Linux" . # 递归搜索所有文件
阅读文件:cat 和 less
cat 会把整个文件输出到终端,适合短文件:
$ cat Documentos/notas.txt
Linux é uma família de sistemas operacionais de código aberto.
Ele usa o kernel criado por Linus Torvalds em 1991.
Eu uso Linux para programar.
É rápido e dá para configurar quase tudo.
对于长文件,less 会在一个可以滚动的界面中打开内容,用方向键或 Page Up、Page Down 翻页。
在其中,/文本 用于查找,n 跳到下一个匹配,q 退出。
$ less /var/log/syslog
统计:wc
$ wc Documentos/notas.txt
4 33 192 Documentos/notas.txt
也就是 4 行、33 个单词、192 个字节。注意,这段文字有 186 个字符,却占 192 个字节:每个带重音的字母在 UTF-8 中占两个字节
(中文字符通常占三个字节)。要统计字符数,使用 wc -m;只统计行数,使用 wc -l。
wc -l 很适合和其他命令组合使用。例如,要知道当前目录下有多少个 .txt 文件:
$ find . -name "*.txt" | wc -l
1
总结
| 命令 | 作用 |
|---|---|
pwd |
显示当前目录 |
ls / ls -a |
列出内容 / 包括隐藏项目 |
cd 文件夹 / cd .. |
进入文件夹 / 返回上一级 |
cd |
回到用户目录 |
find . -name "*.txt" |
按名称查找文件 |
grep "文本" 文件 |
显示包含该文本的行 |
cat 文件 |
显示整个文件 |
less 文件 |
打开文件以便滚动和查找 |
wc -l 文件 |
统计行数 |