
[英]Replace a section of code in .profile with a file using sed or awk
[英]How to replace two code blocks in a file by sed or awk
由于 git 冲突,我想合并两个代码块以接受这两个更改,如下所示。
使用 Atom 这样的编辑器,它可以通过选项“Theirs then ours”(或“Ours then theirs”)解析,我想通过命令行解析。
我想过用 sed 和 awk 但我想不出来。 请告诉我如何通过sed
或awk
或其他解决方案解决此问题。
从这个文件
one
<<<<<<< HEAD
two
three
=======
four
five
>>>>>>> Add develop
喜欢这个。
one
four
five
two
three
我使用sed
两次并尝试如下,但没有得到我想要的结果。
第一次,在以<<<<<<<
开始和以=======
结束>>>>>>>
行之间移动行。 接下来,第二次删除这些<<<<<<<
, =======
, >>>>>>>
行。
结果包含额外的空行。 此外,该方法没有考虑这样的代码块多次出现的情况。
$ sed -E -e '/^<{7}.*$/,/^={7}.*$/{H;d};/^>{7}.*$/{G}' test.txt | sed -E -e '/^[<=>]{7}.*$/{d}'
one
four
five
two
three
你能不能试试以下。
awk '
/>>/ && found1 && found2{
print val2 ORS val1
}
/</{
val1=val2=found2=""
found1=1
next
}
found1 && /=/{
found2=1
next
}
found1 && !found2{
val1=(val1?val1 ORS:"")$0
next
}
found2{
val2=(val2?val2 ORS:"")$0
next
}
1
' Input_file
说明:为以上添加详细的方式说明。
awk ' ##Starting awk program from here.
/>>/ && found1 && found2{ ##Checking condition if line has >> string in it and variable found1 and found2 is NOT NULL then do following.
print val2 ORS val1 ##Printing val2, ORS and val1 variables here.
} ##Closing BLOCK for above condition here.
/</{ ##Checking condition if line has < in it then do following.
val1=val2=found2="" ##Nullifying variables val1,val2 and found2.
found1=1 ##Setting found1 as 1 to be used in further statements from here.
next ##next keyword will skip all further statements from here onward.
} ##Closing BLOCK for above condition here.
found1 && /=/{ ##Checking condition if found1 variable is SET AND line has = in it then do following.
found2=1 ##Setting variable found2 to 1 here.
next ##next will skip all further statements from here,
} ##Closing BLOCK for above condition here.
found1 && !found2{ ##Checking condition ig variable foudn1 is SET and found2 is NOT SET then do following.
val1=(val1?val1 ORS:"")$0 ##Creating variable val1 whose value is keep concatenating its own value with a new line here.
next ##next will skip all further statements from here.
} ##Closing BLOCK for above condition here.
found2{ ##Checking condition ig variable found2 is SET then do following.
val2=(val2?val2 ORS:"")$0 ##Creating variable val2 whose value is keep concatenating to its own value with a new line.
next ##next will skip all further statements from here.
} ##Closing BLOCK for above condition here.
1 ##Mentioning 1 will print edited/non-edited line here.
' Input_file ##Mentioning Input_file name here.
这可能对你有用(GNU sed):
sed -nE '/^<{7}/{:a;n;/^={7}/bb;H;ba;:b;n;/^>{7}/bc;p;bb;:c;z;x;s/.//};p' file
通过设置-n
选项关闭隐式打印,并通过设置-E
选项启用更简单的正则表达式。
收集保留空间中以<<<<<<<
开头的行之后的行,然后打印一行开头=======
之后的行,直到行开始>>>>>>>
然后附加收集到的行保留空间中的行(减去第一个将是换行符的字符)。
注意z
命令,它清空新的保持空间,准备进一步修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.