How to automat editing of several files in Vim?

前端 未结 2 782
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 14:22

I have a multitude of files in each of which I want to, say, delete lines 1 through 55, add a comment leader (e.g., //) on lines 25 through 35, and then save th

相关标签:
2条回答
  • 2020-12-30 14:37

    You can accomplish this elegantly with ed, the unix line editor, the ancestor of vi.

    fix_file () {
      ed -s "$1" <<-'EOF'
        1,55d
        25,35s_.*_// &_
        wq   
    EOF
    }
    

    Now, for each file F you need, just execute fix_file F.

    0 讨论(0)
  • 2020-12-30 14:38

    Despite the fact that using ed or sed is a common practice1 in such cases, sometimes using Vim is much more convenient. Indeed, instead of writing an ed-like script somewhat blindly, it is often easier to first perform the desired manipulations with one of the files interactively in Vim:

    vim -w log.vim file1.txt
    

    and then repeat it on the rest of the files:

    for f in file*.txt; do vim -s log.vim "$f"; done
    

    For your example use case, the log.vim file will likely have contents similar to the following:

    gg55dd:25,35s/^/\/\/ /
    :w %_new
    :q!
    

    Note that to save the file with new name you should not type it directly, but rather use the % substitution, as shown above—otherwise all the modifications of all the following files will be saved to the same file, overwriting its contents every time. Alternatively, you can duplicate the files beforehand and then edit the copies in place (saving each of them by simply issuing the :w command without arguments).

    The advantage of this approach is that you can make all of the changes interactively, ensuring that you are getting the intended result at least on one of the files, before the edits are performed for the rest of them.


    1 Of course, you can use Vim in an ed-like fashion, too:

    for f in file*.txt; do vim -c '1,55d|25,35s/^/\/\/ /|w! '"${f}_new"'|q!' "$f"; done
    
    0 讨论(0)
提交回复
热议问题