缩进与单词匹配的行,然后使用替换打印它们

时间:2015-07-16 15:53:38

标签: linux ubuntu awk sed

我正在尝试将所有open替换为not open。我想打印原始文本,修改后的行缩进并保留原始形式,然后是修改后的表格。

这个命令还不够:

sed 's/open/not open/' file.txt

示例输入:

this is the first line of text
this text is very open
and this is the next line of text 

示例输出:

this is the first line of text
    this text is very open
    this text is very not open 
and this is the next line of text 

2 个答案:

答案 0 :(得分:3)

鉴于此input.txt

this is the first line of text
this text is very open
and this is the next line of text

以下代码

sed '/not open/ b; /open/ { s/^/    /; p; s/open/not open/ }' input.txt

输出:

this is the first line of text
    this text is very open
    this text is very not open
and this is the next line of text

第一个条款只是跳过匹配not open的任何一行(这意味着读取行The door is not open. Do open it.没有替换)。 b命令跳到脚本的末尾。如果您不想要这种逻辑,可以省略此部分。

第二个句子在任何其他行上提到open,并对其执行三个操作:缩进四个空格,立即打印,然后进行替换。最后,sed会在评估结束时自动打印该行(已修改与否,即使已经打印过)。

答案 1 :(得分:1)

这可能适合你(GNU sed):

 sed '/\<open\>/!b;s/^/\t/p;s/\<open\>/not &/g' file

任何不包含单词open的行都会正常打印。否则,在该行的开头插入一个标签并打印原始行,然后将所有open替换为not open并打印。