views:

115

answers:

4

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

+7  A: 

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.
Amarghosh
Thanks.. that worked like a breeze! and thanks again for the very good explaination..
Myth
@Myth Add a `c` at the end to make it prompt for each line: you can hit y/n to replace or skip the line `:%s/^\(.*\)$/"\1"/c`
Amarghosh
Thats quite handy.. can you point me to some good resources to learn regx ? Sorry for the diversion from the main subject.
Myth
I learned from [this tutorial](http://www.regular-expressions.info/tutorial.html). Check out this [SO question](http://stackoverflow.com/questions/3193977/id-love-to-learn-regular-expressions-what-would-you-suggest-me-to-start-off-wit/3194013#3194013) and the one it is marked as a duplicate of for more links. [Expresso](http://www.ultrapico.com/Expresso.htm) is quite useful.
Amarghosh
+1  A: 

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

cat foo.txt | sed s/^\(.*\)$/"\1"/g
Mainguy
+7  A: 

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.)

George Bergman
+1  A: 

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.

nicholas a. evans
`yss"` is actually five keystrokes, if you count the <shift> for the double quote. ;-) It's still a whole lot faster than typing out a regular expression.
nicholas a. evans