Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sed question? 1

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
US
I don't understand this. I have a text file with this in it:
Code:
    1234
(that's 4 spaces, not a tab)

If I run this command to remove the spaces, it works:
Code:
sed -i -e "s/^[ ]*//" out.txt
but if I run this command it doesn't work:
Code:
sed -i -e "s/^[ ]+//" out.txt

+ means 1 or more of the previous characters, and there are definitely 1 or more spaces, so why doesn't the 2nd command work?
 
You're correct, but in this case sed thinks that you're using the + as a character to match, rather than to denote one or more occurrences. Try escaping that + and it should work.
Code:
sed -i -e "s/^[ ][COLOR=red]\[/color]+//" out.txt
 
What the hell?? That worked.
Shouldn't that tell it to look for a space followed by a '+' if you escape it?
Why didn't I have to escape the * then?
 
Good question. I actually never bothered to look that up until just now.

It appears the reason is that, by default, sed uses Basic Regular Expressions (BRE), which do not include +, ?, and a few others. Those are only in Extended Regular Expressions (ERE). Thus sed treats them as normal characters. It appears that escaping an ERE metacharacter will cause sed to treat give them special treatment.

Alternatively, you can just tell sed to use ERE by passing it the -r option. That way you don't even have to worry about it.
 
Cool thanks. I thought it had to be something weird like that.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top