交换文件的产生可能有几种情况:
1,当你用vim编辑一个文件时,发生突发事件,导致窗口关闭,或者系统崩溃重启;
2,另一个vim正在编辑该文件;
下面具体说下第一种情况:
原文件:
# cat a.txt This is a test for vim. line 1 line 2 line 3
在文件里面添加了新的内容:
This is a test for vim. line 1 line 2 line 3 ### Add new lines: Line 4 Line 5 Line 6
还没来得及保存,突然终端就断开了,导致.swp文件产生
[[email protected] ~]# ll -a total 316 drwx------ 5 xielf xielf 4096 Jan 7 13:12 . drwxr-xr-x 7 root root 4096 Jan 14 2014 .. -rw-r--r-- 1 root root 45 Jan 7 13:10 a.txt -rw-r--r-- 1 root root 12288 Jan 7 13:11 .a.txt.swp
查看原文件内容,发现是最原始的数据,没有我们做过修改的内容
[[email protected] ~]# cat a.txt This is a test for vim. line 1 line 2 line 3
查看swp文件:
[[email protected] ~]# vim -r .a.txt.swp#-r 读取交换文件 会看到下面一段提示: Using swap file ".a.txt.swp" Original file "/root/a.txt" E308: Warning: Original file may have been changed Recovery completed. You should check if everything is OK. (You might want to write out this file under another name and run diff with the original file to check for changes) Delete the .swp file afterwards. Press ENTER or type command to continue 按ENTER继续: This is a test for vim. line 1 line 2 line 3 ### Add new lines: Line 4 Line 5 Line 6
swp文件里面的内容有最后编辑的最新内容,那我们要把它恢复到a.txt,先退出。
打开a.txt源文件:
[[email protected] ~]# vim a.txt E325: ATTENTION Found a swap file by the name ".a.txt.swp" owned by: root dated: Wed Jan 7 13:11:26 2015 file name: ~root/a.txt modified: YES user name: root host name: test process ID: 29908 While opening file "a.txt" dated: Wed Jan 7 13:10:00 2015 (1) Another program may be editing the same file. If this is the case, be careful not to end up with two different instances of the same file when making changes. Quit, or continue with caution. (2) An edit session for this file crashed. If this is the case, use ":recover" or "vim -r a.txt" to recover the changes (see ":help recovery"). If you did this already, delete the swap file ".a.txt.swp" to avoid this message. Swap file ".a.txt.swp" already exists! [O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort: ## O 以只读方式打开 E 继续编辑,如果该文件正在被另一个vim编辑,你将可能得到两个版本 R 从swp文件中恢复 D 删除swp文件,如果发现swp文件和原文件内容一致,没有任何改动,可以用该操作。 Q 退出 A 类似于退出,但它同时会撤销后续命令的执行,在载入一个脚本编辑多个文件时比较有用。
上面提示显示:modified: YES,说明有改动,我们从swp文件中恢复,按shift+r,接着按回车就恢复了swp文件中的内容。
然后保存下,这样才能将swp的内容保存到原文件里面,保存退出后,记得将swp文件删除,不然下次还会提示。
确认下恢复后的文件:
[[email protected] ~]# cat a.txt This is a test for vim. line 1 line 2 line 3 ### Add new lines: Line 4 Line 5 Line 6
OK,没问题,已经恢复了修改后的文件。
试想一下,如果我们正在配置某个配置文件,突然导致vim编辑异常关闭,导致了交换文件的产生,那我们之前做的大量的修改就白做了,所以知道如何恢复swp文件是很有必要的哦,避免过多的重复工作。
时间: 2024-10-10 20:03:54