Adding characters at the start and end of each line in a file

后端 未结 4 981
抹茶落季
抹茶落季 2021-01-30 02:32

What is the best way to add some characters at the start and end of each line? Can it be done using Vim, or some other way?

相关标签:
4条回答
  • The two answers suggesting %s are perfect, and I expect you'll learn to love %s and use it often. But if you find yourself wanting to surround other blocks of text frequently, you owe it to yourself to check out the surround.vim plugin, which would allow you to do what you asked for with the following four keystrokes: yss" And there are many other useful built-in surround targets. For example, to surround the current word with double quotes: csw", and to change the surrounding single quotes to double quotes: cs'".

    surround.vim is one of my favorite vim plugins, and I use it daily.

    0 讨论(0)
  • 2021-01-30 02:59

    In vim, you can do

    :%s/^\(.*\)$/"\1"/
    
    • s/regex/replace/ is vim command for search n replace.
    • % makes it apply throughout the file
    • ^ and $ denotes start and end of the line respectively.
    • (.*) captures everything in between. ( and ) needs to be escaped in vim regexes.
    • \1 puts the captured content between two quotes.
    0 讨论(0)
  • 2021-01-30 03:03

    simpler:

    %s/.*/"&"

    Explanation: By default, a pattern is interpreted as the largest possible match, so .* is interpreted as the whole line, with no need for ^ and $. And while \(...\) can be useful in selecting a part of a pattern, it is not needed for the whole pattern, which is represented by & in the substitution. And the final / in a search or substitution is not needed unless something else follows; though leaving it out could be considered laziness. (If so, I'm lazy.)

    0 讨论(0)
  • 2021-01-30 03:03

    better util would be sed (especially if you need to script it)

    cat foo.txt | sed s/^\(.*\)$/"\1"/g
    
    0 讨论(0)
提交回复
热议问题