Question

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

Was it helpful?

Solution

Try:

sed -e 's/^/"/' -e 's/$/"/' file

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top