1

Could anyone tell me a regex that matches the beginning or end of a line? e.g. if I used sed 's/[regex]/"/g' filehere the output would be each line in quotes? I tried [\^$] and [\^\n] but neither of them seemed to work. I'm probably missing something obvious, I'm new to these

Dom Brown
  • 201
  • 1
  • 2
  • 9

3 Answers3

4

Try:

sed -e 's/^/"/' -e 's/$/"/' file
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Matthias
  • 724
  • 7
  • 14
3

To add quotes to the start and end of every line is simply:

sed 's/.*/"&"/g'

The RE you were trying to come up with to match the start or end of each line, though, is:

sed -r 's/^|$/"/g'

Its an ERE (enable by "-r") so it will work with GNU sed but not older seds.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

matthias's response is perfectly adequate, but you could also use a backreference to do this. if you're learning regular expressions, they are a handy thing to know.

here's how that would be done using a backreference:

sed 's/\(^.*$\)/"\1"/g' file

at the heart of that regex is ^.*$, which means match anything (.*) surrounded by the start of the line (^) and the end of the line ($), which effectively means that it will match the whole line every time.

putting that term inside parenthesis creates a backreference that we can refer to later on (in the replace pattern). but for sed to realize that you mean to create a backreference instead of matching literal parentheses, you have to escape them with backslashes. thus, we end up with \(^.*$\) as our search pattern.

the replace pattern is simply a double quote followed by \1, which is our backreference (refers back to the first pattern match enclosed in parentheses, hence the 1). then add your last double quote to end up with "\1".

nullrevolution
  • 3,937
  • 1
  • 18
  • 20
  • 1
    ^.*$ is the same as .*, the ^ and the $ are redundant. You also don't need to backreference a specific matching string when the whole RE matches - that's what & is for. – Ed Morton Jan 04 '13 at 20:39
  • agreed, but i threw them in there for the sake of clarity. my answer was more intended to show how to use a backreference rather than how to address the specific scenario in question. – nullrevolution Jan 04 '13 at 20:52
  • that's fine but it would have been useful to also show the OP the answer to his specific question so he doesn't think this is the best way to do that. – Ed Morton Jan 04 '13 at 20:53