简体   繁体   中英

issues with sed on Mountain Lion

I am trying to delete a line on a file that looks like this:

test 1800 IN CNAME mydomain.com.

I am using sed on Mountain Lion and I am trying the following but I keep getting no errors, however the line is not deleted.

sed -i -e '/$regex/d' $file

or

sed -i "" -e '/$regex/d' $file

Where the $regex is the expression containing the line mention above and the $file is the name of the file where the line is.

Any help Will be appreciate it.

This is a near duplicate of Sed command find and replace in file ... , and the most portable answer is the same as there:

sed -e '/$regex/d' $file >$file.tmp && mv $file.tmp $file

...for the reasons, and with the advantages, given there. When you're concerned about portability, the POSIX spec is a great resource, since it describes a common subset of unix commands, which is often frustratingly restricted, but which is pretty reliably present in all the unixes one is likely to come across.

Mountain Lion (v10.8.2) works just fine with sed -i "" -e '/$regex/d' $file

[Mar 12 17:22] [jnovack@growlithe ~]$ more test.php
<?php
echo "Test php echo 1";
echo "Test echo 2";
?>
[Mar 12 17:22] [jnovack@growlithe ~]$ sed -i "" -e "/php/d" test.php
[Mar 12 17:22] [jnovack@growlithe ~]$ more test.php
echo "Test echo 2";
?>

The most likely problem, it seems to me, is that you have a shell variable $regex which contains the pattern to be searched for and deleted, but your single quotes prevent the shell expanding it. You likely need to use:

sed -i .bak -e "/$regex/d" $file

(BSD sed on Lion and Mountain Lion supports the -i option. The manual page recommends against a zero-length back-up extension.)

-i extension

Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM