mac中的sed用法的区别

来源:互联网 发布:蒙泰软件视频教程 编辑:程序博客网 时间:2024/06/11 16:44
我只想说。。CSDN的新编辑器很好用的样子啊哦。。。command+Q退出了 呵呵呵呵呵这样对待我们mac用户真的好吗 ๑•́₃•̀๑

以下正文


大家都知道,mac是BSD的扩展,所以很多命令和Linux是不一样的。当然Linux也有它自己的扩展,大家肯定都是用户能更好更安全的使用shell命令。

但是Mac的sed的确不太好用,手册也写的不是很懂。还没有example…

这里做一些并不完全的总结。 所以本片算是原创吧。引用我会提到的。

- sed -i s

其实sed的替换 s 也是有问题的 不过我在写shell脚本的时候,没有发现问题,有很多博客提到了这个问题
如这篇博客: mac 下sed命令的-i参数
大体的意思是说,Linux中可选的参数 即 备份出来后的文件名 mac中是强制的。可能是为了安全吧。毕竟你直接改一个文件可能会有安全隐患。所以很多人的解决办法是,加一个 ” 就是空,就可以了。

- sed -i a

这块就比较复杂了。我开始没有找到相关的解决方案,看手册,说是什么[1 addr]a/ 然而试了很多办法,也并没有卵用。

请大家看我血淋淋的试验现场:

BertiedeMacBook-Pro: sed =a ‘1’ “aaa” a.txt
sed: 1: “=a”: extra characters at the end of = command
BertiedeMacBook-Pro: sed -i “” ‘a/1/Dog/g’ example.txt
sed: 1: “a/1/Dog/g”: command a expects \ followed by text
BertiedeMacBook-Pro:sed -i “” ‘a\1\Dogg’ example.txt
sed: 1: “a\1\Dogg”: extra characters after \ at the end of a command
BertiedeMacBook-Pro: sed -i “” ‘s/1/Dog/g’ a.txt
BertiedeMacBook-Pro: vim a.txt
BertiedeMacBook-Pro: man set
BertiedeMacBook-Pro: man sed
BertiedeMacBook-Pro: sed -i “” ‘1 s/1/Dog/g’ a.txt
BertiedeMacBook-Pro: vim a.txt
BertiedeMacBook-Pro: sed -i “” ‘1 a/dddd’ a.txt
sed: 1: “1 a/dddd”: command a expects \ followed by text
BertiedeMacBook-Pro: sed ‘1 a/dddd’ a.txt
sed: 1: “1 a/dddd”: command a expects \ followed by text
BertiedeMacBook-Pro: man sed
BertiedeMacBook-Pro: sed 1 a/dddd a.txt
sed: 1: “1”: command expected
BertiedeMacBook-Pro: sed [1] a/dddd a.txt
sed: 1: “[1]”: invalid command code [
BertiedeMacBook-Pro: sed ‘1’ a/dddd a.txt
sed: 1: “1”: command expected
BertiedeMacBook-Pro: sed -i “” ‘1’ ‘a/dddd’ a.txt
sed: 1: “1”: command expected
BertiedeMacBook-Pro: sed -i “” ‘1 ‘a/dddd’ a.txt
>
BertiedeMacBook-Pro: sed -i “” ‘1 a/dddd’ a.txt
sed: 1: “1 a/dddd”: command a expects \ followed by text
BertiedeMacBook-Pro:game Bertie$ sed -i “” ‘1 a/”dddd”’ a.txt
sed: 1: “1 a/”dddd”“: command a expects \ followed by text
BertiedeMacBook-Pro: sed -i “” ‘a/1/dddd’ a.txt
sed: 1: “a/1/dddd”: command a expects \ followed by text

其实还有很多。。。
我当时在校园里的长椅上,写着玩,也没有网络。冻的我都急红了眼,毫无逻辑可言。
后来上google查了下,有认识这么建议的

到**网站,下载标准sed,命名为sad,然后#alias sad sed

hahah
sad…

然后后来终于发现再另一个问答,有人得到了解决办法

As a GNU extension, if between the a and the newline there is other than a whitespace-\ sequence, then the text of this line, starting at the first non-whitespace character after the a, is taken as the first line of the text block. (This enables a simplification in scripting a one-line add.) This extension also works with the i and c commands.
Thus, to be portable with your sed syntax, you will need to include a newline after the a\ somehow. The easiest way is to just insert a quoted newline:

[Math Processing Error] and > are shell prompts). If you find that a pain, bash [1] has the $’ ’ quoting syntax for inserting C-style escapes, so just use

sed -e ‘a\’$’\n”text’.1
so..终于搞定了


  1. and mksh (r39b+) and some non-bash bourne shells (e.g., /bin/sh in FreeBSD 9+) ↩
1 0