gpt4 book ai didi

bash - 如何通过 sed 或 awk 替换文件中的两个代码块

转载 作者:行者123 更新时间:2023-12-02 23:50:55 24 4
gpt4 key购买 nike

我想 merge 两个代码块以接受由于 git 冲突而导致的两个更改,如下所示。

使用像Atom这样的编辑器,它可以通过选项“他们的然后我们的”(或“我们的然后他们的”)来解决,我想通过命令行解决。

我想过使用 sed 和 awk 但我想不出来。请告诉我如何解决这个问题sedawk ,或其他解决方案。

从此文件

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.

关于bash - 如何通过 sed 或 awk 替换文件中的两个代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59205891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com