Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed/regex: How to match a '<' or '>' in a string

Tags:

regex

sed

I'm looking to match all less than ('<') or greater than ('>') signs in a file using sed. I only want to match the single character

My goal is to replace them with ' <' and '> ' (ensure they have white space around them so I can parse them easier) respectively.

For example, it would match: (without space within the tags)

< p >Hey this is a paragraph.< /p >< p >And here is another.< /p >

.. and turn it into (note the spaces)

 < p > Hey this is a paragraph. < /p >  < p > And here is another. < /p > 



Here's what my initial (wrong) guess was:

sed 's/<{1}|>{1}/ <> /' ...


It matches the whole word/line, which is not desired, and it also does not replace correctly.

Anyways, any help would be appreciated! Thanks!

like image 361
jiman Avatar asked Dec 21 '11 15:12

jiman


People also ask

How do you match a character in sed?

Matches any single character in list : for example, [aeiou] matches all vowels. A list may include sequences like char1 - char2 , which matches any character between (inclusive) char1 and char2 . A leading ^ reverses the meaning of list , so that it matches any single character not in list .

Can you use regex with sed?

Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi.

Can you use sed on a string?

The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.


1 Answers

Try two substitutions to make it easier:

sed 's/</ </g ; s/>/> /g' file
like image 77
sidyll Avatar answered Oct 02 '22 12:10

sidyll