vim编辑文件时,系统崩溃后的文件恢复

描述 :

        在vim编辑文件时,连接异常断开,导致所做的修改没有保存。这时可以通过文件相同目录下的.swp文件来恢复。如果是自己的连接异常断开,确定不需要保存之前的修改,可以直接删掉.swp文件即可。

vim在编辑文件时,是在work buffer中进行的,缓存中的信息有存放在.swp文件(原文件名加.swp结尾的文件),当连接异常断开,缓存中的信息丢失,但.swp文件依然存在,可以通过这个文件来进行数据恢复。如果原文件是正常关闭,.swp文件会自动删除。在正常的修改操作期间,可以不需要.swp文件(比如被误删除了),数据仍能正常从work buffer保存到磁盘,其隐患就是,如果连接异常断开就不能恢复了。

模拟修改文件时异常断开情境,查看文件内容-->修改文件内容-->异常断开连接:

[root@ ~]# cat test.txt
oh,this is
ddddd
11111
22222

[root@ ~]# vim test.txt
oh,this is
ddddd
11111
22222
xxxxx

查看需要恢复文件的.swp临时交换文件

[root@ ~]# ll -a  |grep test.txt
-rw-r--r--.  1 root root    30 Jul  8 09:03 test.txt
-rw-r--r--.  1 root root 12288 Jul  8 09:04 .test.txt.swp

以恢复模式(-r参数)打开文件 ,如下是恢复提示,建议先将恢复后的文件内容保存在另一个文件中,这时原文件不受影响,内容还是修改前的内容,再比较两个文件的内容,确认之前所做的修改。

[root@ ~]# vim -r  test.txt

Using swap file ".test.txt.swp"
Original file "~/test.txt"
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

保存到另一个文件退出,再查看文件:

:w  test_r.txt
:q

[root@ ~]# ll -a  |grep test
-rw-r--r--.  1 root root    36 Jul  8 09:50 test_r.txt
-rw-r--r--.  1 root root    30 Jul  8 09:03 test.txt
-rw-r--r--.  1 root root 12288 Jul  8 09:04 .test.txt.swp

比较两个文件的差异,可以看到test_r.txt文件中是多了最后一行的内容:

[root@ ]# diff -y  test.txt   test_r.txt
oh,this is                oh,this is
ddddd                     ddddd
11111                     11111
22222                     22222
                        > xxxxx

比较完文件内容后,可以确定是否要保存.swp中的信息;可以用-r参数打开原文件,直接:wq保存即可。再删掉.swp文件。

附:

vim中-r参数的使用:

[root@ ~]# man  vim
-r          List swap files, with information about using them for recovery.

-r {file}   Recovery mode.  The swap file is used to recover a crashed editing  session.
            The  swap file is a file with the same filename as the text file with ".swp"
            appended.  See ":help recovery".

查看当前目录下的.swp文件:

[root@ ~]#  vim -r
Swap files found:
   In current directory:
1.    .test.txt.swp
          owned by: root   dated: Mon Jul  8 09:04:05 2019
         file name: ~root/test.txt
          modified: YES
         user name: root   host name: kaka1
        process ID: 3168
   In directory ~/tmp:
      -- none --
   In directory /var/tmp:
      -- none --
   In directory /tmp:
      -- none --

以恢复模式打开test.txt文件,这时显示的是.swp文件中的信息:

[root@ ~]# vim -r  test.txt

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值