Update:
您可以使用以下内容sed
命令甚至替换最后一个,
之前CONSTRAINT
block:
sed -r '/,/{N;/CONSTRAINT/{:a;N;/GO/!ba;s/([^,]+).*/\1\n)/};/CONSTRAINT/!n}' input.sql
让我将其解释为多行脚本:
# Search for a comma
/,/ {
# If a command was found slurp in the next line
# and append it to the current line in pattern buffer
N
# If the pattern buffer does not contain the word CONSTRAINT
# print the pattern buffer and go on with the next line of input
# meaning start searching for a comma
/CONSTRAINT/! n
# If the pattern CONSTRAINT was found we loop until we find the
# word GO
/CONSTRAINT/ {
# Define a start label for the loop
:a
# Append the next line of input to the pattern buffer
N
# If GO is still not found in the pattern buffern
# step to the start label of the loop
/GO/! ba
# The loop was exited meaning the pattern GO was found.
# We keep the first line of the pattern buffer - without
# the comma at the end and replace everything else by a )
s/([^,]+).*/\1\n)/
}
}
您可以将上述多行脚本保存在文件中并使用以下命令执行它
sed -rf script.sed input.sql
您可以使用以下内容sed
命令:
sed '/CONSTRAINT/{:a;N;/GO/!ba;s/.*/)/}' input.sql
该模式搜索包含以下内容的行/CONSTRAINT/
。如果找到该模式,则开始将命令块包裹在{ }
。在块中我们首先定义一个标签a
通过:a
。我们通过以下方式得到下一行输入N
并将其附加到模式缓冲区。除非我们找到模式/GO/!
我们将继续标签a
使用分支命令b
。如果图案/GO/
发现我们只需将缓冲区替换为)
.
另一种方法是使用 FredPhil 建议的范围:
sed '/CONSTRAINT/,/GO/{s/GO/)/;te;d;:e}'