sed笔记
通过 sed 在匹配行后面添加一行文本
-
实例
匹配到SET row_security = off;这一行后插入指定的文本。
假设你想把xxxxx替换为-- This is a comment -
方法:
sed '/SET row_security = off;/a\-- This is a comment' *create_obj.sql
参数解释:
/SET row_security = off;/:匹配包含SET row_security = off;的行。a\:表示在匹配行的下一行添加文本。-- This is a comment:插入的文本内容。
通过 sed 在匹配行后面添加多行文本
如果你想插入多行,可以这样:
sed '/SET row_security = off;/a\
-- Line 1 of the comment\
-- Line 2 of the comment' *create_obj.sql
注意:
- 使用
\分隔多行文本。 - 确保每一行末尾没有多余空格,否则可能导致
sed报错。
通过 Heredoc 实现
结合 Heredoc 可以更方便地插入多行文本,尤其是当插入的内容比较复杂时。以下是一个基于 sed 和 Heredoc 的示例:
示例:插入多行文本
假设你想在匹配到 SET row_security = off; 后插入以下多行文本:
-- This is the first line
-- This is the second line
-- End of comment
你可以使用如下方法:
cat <<EOF | sed '/SET row_security = off;/r /dev/stdin' -i *create_obj.sql
-- This is the first line
-- This is the second line
-- End of comment
EOF
参数说明
cat <<EOF和EOF:- 用来创建一个 Heredoc,可以直接在命令中书写多行文本。
/SET row_security = off;/r /dev/stdin:r /dev/stdin:从标准输入读取内容并在匹配行之后插入。
-i:- 表示直接修改文件内容,而不输出到标准输出。
*create_obj.sql:- 匹配需要处理的文件。
运行后的效果
假设原始文件内容如下:
SET row_security = off;
CREATE TABLE my_table (
id SERIAL PRIMARY KEY
);
运行上述命令后,文件内容变为:
SET row_security = off;
-- This is the first line
-- This is the second line
-- End of comment
CREATE TABLE my_table (
id SERIAL PRIMARY KEY
);
优点
- 使用 Heredoc,可以在命令中灵活地书写多行文本。
- 与
sed配合,适合批量修改文件。
如果你还有其他需求,欢迎进一步讨论!
如果需要直接修改文件
使用 -i 参数直接修改文件:
sed -i '/SET row_security = off;/a\-- This is a comment' *create_obj.sql

浙公网安备 33010602011771号