Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed regex problem on Mac, works fine on Linux

Tags:

linux

macos

sed

This works fine on Linux (Debian):

sed -e 's,^[ \t]*psd\(.*\)\;,,' 

On mac, I believe I have to use the -E flag, instead of -e:

sed -E 's,^[ \t]*psd\(.*\)\;,,'

but the regexp does not match, and hence does not remove the lines I want.

Any tips on how to solve this?

Sample input:

apa
bepa
    psd(cepa);
depa psd(epa);
  psd(fepa gepa hepa);

For that input, the expected output is:

apa
bepa
depa psd(epa);
like image 315
JohnSmith Avatar asked Jul 20 '11 11:07

JohnSmith


People also ask

Does sed command work on Mac?

We know that the sed on Mac OS is the POSIX sed, which cannot use many options. On the other hand, GNU sed is very convenient. For example, GNU sed interprets escape sequences like \t , \n , \001 , \x01 , \w , and \b . OSX's sed and POSIX sed only interpret \n (but not in the replacement part of s ).

What is sed command in Mac?

SED is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits, SED works by making only one pass over the input(s), and is consequently more efficient.

Does sed work with regex?

The sed command has longlist of supported operations that can be performed to ease the process of editing text files. It allows the users to apply the expressions that are usually used in programming languages; one of the core supported expressions is Regular Expression (regex).

What type of regex does sed use?

As Avinash Raj has pointed out, sed uses basic regular expression (BRE) syntax by default, (which requires ( , ) , { , } to be preceded by \ to activate its special meaning), and -r option switches over to extended regular expression (ERE) syntax, which treats ( , ) , { , } as special without preceding \ .


2 Answers

The -E flag means to use extended regular expressions. You should just use -e, as on Linux. The sed in Mac OS X is based on BSD sed, so doesn't have the GNU extensions.

After copying your sample input:

[~ 507] pbpaste | sed -e 's,^[[:space:]]*psd\(.*\);,,'
apa
bepa

depa psd(epa);
like image 169
Michael J. Barber Avatar answered Oct 29 '22 20:10

Michael J. Barber


The '\t' is not standard in 'sed', it is a GNU extension.

To match a 'tab', you need to put a real 'tab' in your script. This is easy in a file, harder in shell.

The same problem can happen in AIX, Solaris and HP-UX or other UNIXes.

like image 23
jfg956 Avatar answered Oct 29 '22 20:10

jfg956