在 solaris 上使用 sed 将一行替换为两行
Using sed on solaris to replace one line by two lines
我想将所有出现的 #include <string>
替换为 #include <string>
,然后是下一行的 using namespace std;
。
我如何在 Solaris 上使用 sed 处理几个文件?
例如,假设我有几个类似于下面的头文件:
....
#include <string>
....
我想用 #include <string>
和 using namespace std;
替换所有出现的 #include <string>
,如下所示:
....
#include <string>
using namespace std;
....
$ cat some-file
/* code code code */
#include <string>
/* code code code */
$ sed '/#include <string>/a using namespace std;' some-file
/* code code code */
#include <string>
using namespace std;
/* code code code */
解释:/#include <string>/
搜索“#include <string>
”,然后命令a
a附加字符串“using namespace std;
”。
另见 man sed
。
sed '/#include <string>/a\
using namespace std;
' file
在匹配的换行符之后追加 a\
并添加带有换行符的字符串。
可能最好的解决方案是使用 /usr/xpg4/bin/sed
,但如果您想使用旧版本,请记住旧版本 sed
对换行符非常讲究。您可能需要在 sed 命令中使用文字换行符。尝试:
$ sed '/#include <string>/a\
using namespace std;
' input-file > output-file
另一种选择是:
$ echo using namespace std; > tmp-file
$ sed '/#include <string>/rtmp-file' input-file > output-file
sed 用于在单行上进行简单替换,仅此而已。对于其他任何你应该使用 awk:
$ awk '{print} /#include <string>/{print "using namespace std;"}' file
....
#include <string>
using namespace std;
....
以上将适用于所有系统上的所有 awk,除了旧的、损坏的 awk(/bin/awk 在 Solaris 上)。在 Solaris 上使用 /usr/xpg4/bin/awk(几乎是 POSIX 的 awk)或 nawk(较旧的,功能较差的 awk)。
我想将所有出现的 #include <string>
替换为 #include <string>
,然后是下一行的 using namespace std;
。
我如何在 Solaris 上使用 sed 处理几个文件?
例如,假设我有几个类似于下面的头文件:
....
#include <string>
....
我想用 #include <string>
和 using namespace std;
替换所有出现的 #include <string>
,如下所示:
....
#include <string>
using namespace std;
....
$ cat some-file
/* code code code */
#include <string>
/* code code code */
$ sed '/#include <string>/a using namespace std;' some-file
/* code code code */
#include <string>
using namespace std;
/* code code code */
解释:/#include <string>/
搜索“#include <string>
”,然后命令a
a附加字符串“using namespace std;
”。
另见 man sed
。
sed '/#include <string>/a\
using namespace std;
' file
在匹配的换行符之后追加 a\
并添加带有换行符的字符串。
可能最好的解决方案是使用 /usr/xpg4/bin/sed
,但如果您想使用旧版本,请记住旧版本 sed
对换行符非常讲究。您可能需要在 sed 命令中使用文字换行符。尝试:
$ sed '/#include <string>/a\
using namespace std;
' input-file > output-file
另一种选择是:
$ echo using namespace std; > tmp-file
$ sed '/#include <string>/rtmp-file' input-file > output-file
sed 用于在单行上进行简单替换,仅此而已。对于其他任何你应该使用 awk:
$ awk '{print} /#include <string>/{print "using namespace std;"}' file
....
#include <string>
using namespace std;
....
以上将适用于所有系统上的所有 awk,除了旧的、损坏的 awk(/bin/awk 在 Solaris 上)。在 Solaris 上使用 /usr/xpg4/bin/awk(几乎是 POSIX 的 awk)或 nawk(较旧的,功能较差的 awk)。