• Uncategorized

About regex : Regex-with-sed-to-search-in-files

Question Detail

I want to search recursiv in files for a given pattern and replace them. The search is for a string like “[‘DB’][‘1’][‘HOST’] = ‘localhost'”. If testing the regex the following doesn’t print anything. Can’t see an error in this regex? Could anyone help?

sed -n '/\[\'HOST\'\]\s?=\s?(?:\'|")(.+)(?:\'|")/p' /path/to/file

Question Answer

POSIX regex does not support non-capturing groups. Besides, you have not specified the -E option and the pattern is parsed as a BRE POSIX pattern where the capturing parentheses should be escaped. Also, the single quotes cannot be escaped to be used in a sed regex pattern, use \x27 instead.

Use

sed -En '/\[\x27HOST\x27\]\s?=\s?[\x27"][^\x27"]+[\x27"]/p'

See an online demo:

s="a string like ['DB']['1']['HOST'] = 'localhost'."
sed -En '/\[\x27HOST\x27\]\s?=\s?[\x27"][^\x27"]+[\x27"]/p' <<< "$s"

Besides, instead of \s, it might be a good idea to use [[:space:]].

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.