Skip to content

Linux 文件操作:读取、复制、改名与删除 ​

本页从一个空练习目录开始,在 Debian 13 容器中逐步创建、写入、复制和删除同一份文件。下列命令不需要 root。

bash
mkdir -p /tmp/linux-walkthrough/file
cd /tmp/linux-walkthrough/file

若目录已有同名文件,换一个新的练习目录,避免覆盖已有资料。

创建文件 ​

bash
touch notes.txt
ls -l notes.txt

接着执行 wc -c notes.txt,本次输出 0 notes.txt,说明新文件是 0 字节。文件已存在时 touch 更新时间,不会清空内容。

写入内容 ​

bash
printf 'first line\n' > notes.txt
printf 'second line\n' >> notes.txt
cat notes.txt

本次 cat 输出:

text
first line
second line

> 覆盖,>> 追加。下一步用 head 和 tail 分别取首尾。权限不足时 shell 重定向会先失败,给 printf 加 sudo 并不能自动解决目标权限问题。

查看文件内容 ​

bash
head -n 10 notes.txt
tail -n 10 notes.txt
cat notes.txt

这里只写了两行,所以 head -n 10 和 tail -n 10 都会显示全文。把参数改小,区别就清楚了:

bash
head -n 1 notes.txt
tail -n 1 notes.txt

本次依次输出 first line 和 second line。

大文件可用 less notes.txt,按 /关键词 查找、q 退出;文件不存在时先核对 pwd 和 ls。

复制/拷贝文件 ​

bash
cp -i notes.txt notes-copy.txt
cmp notes.txt notes-copy.txt

本次 cmp 没有输出。紧接着执行 printf 'cmp status: %s\n' "$?",得到 cmp status: 0,两份内容相同。必须紧接着读取 $?,否则拿到的是另一条命令的状态。

-i 在覆盖前询问;复制目录可用 cp -a 来源目录 目标目录,已有目标目录会影响最终层级。

移动文件 ​

bash
mv -i notes-copy.txt notes-archived.txt
ls -l notes-archived.txt

本次用 ls -1 看文件名:

text
notes-archived.txt
notes.txt

notes-copy.txt 已改名,原始 notes.txt 仍在。mv 同时可用于改名;检查目标是否已有同名文件。它不是自动保留旧版本的备份工具。

删除文件 ​

bash
ls -l -- notes-archived.txt
rm -i -- notes-archived.txt

本次提示 rm: remove regular file 'notes-archived.txt'?,输入 y 并回车。再执行:

bash
test ! -e notes-archived.txt
printf 'removed status: %s\n' "$?"

输出 removed status: 0,说明归档副本已移除。保留 notes.txt,下一篇可继续练权限。删除通常不进入回收站。-- 结束选项,适合处理以短横线开头的文件名。test ! -e notes-archived.txt 的退出码为 0。

Linux 学习路径 ​

路径问题看目录结构,访问失败看权限,打包备份看 tar。

官方资料 ​

最近更新