Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

replace

vim

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?

like image 804
Myth Avatar asked Jul 10 '10 10:07

Myth


People also ask

How do you add a character at the end of every line in Unix?

You just need 's/$/\//' - the $ anchors the pattern to the end of the line, but it's not an actual character that can be replaced.

How to insert text at the beginning and end of each line?

Insert text at the beginning and end of each line notepad++ Step 2: To add Text at the Start of each line Press Ctrl+F to open Find window, click on the Replace tab, check that you have selected Regular Expression option, now add ^ in the Find textbox and the text you want at the start of each line in the Replace textbox, and click Replace all.

How to add characters at start&end of every line?

How to add characters at start & end of every line in Notepad++ 1 Press Ctrl + H to bring up the Replace dialog box (or Ctrl + F and click the tab 2 Select the Regular Expression Radio Button More ...

How do I add text to the end of a file?

SED/AWK – Add to the End. Use the following commands to append some SUFFIX (some text or character) to the end of every line in a FILE: $ awk '{print $0"SUFFIX"}' FILE – or – sed 's/$/SUFFIX/' FILE SED/AWK – Add to the Beginning and End

How do I add a prefix to the beginning of a line?

SED/AWK – Add to the Beginning. Use the below commands to append some PREFIX (some text or character) to the beginning of every line in a FILE: $ awk '{print "PREFIX"$0}' FILE. – or –. $ sed 's/^/PREFIX/' FILE. Cool Tip: Do not be a bore!


2 Answers

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.
like image 116
Amarghosh Avatar answered Oct 03 '22 16:10

Amarghosh


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

like image 35
George Bergman Avatar answered Oct 03 '22 16:10

George Bergman