我有下面的代码
CREATE TABLE Table1(
column1 double NOT NULL,
column2 varchar(60) NULL,
column3 varchar(60) NULL,
column4 double NOT NULL,
CONSTRAINT Index1 PRIMARY KEY CLUSTERED
(
column2 ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY
) ON PRIMARY
GO
GO
我想更换
CONSTRAINT Index1 PRIMARY KEY CLUSTERED
(
column2 ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY
) ON PRIMARY
GO
带有
)
您不能假设GO是文件的最后一个字符。Go之后可以有另一个表脚本。我怎么能用单sed或awk做到这一点。
更新:
您可以使用以下sed
命令来替换CONSTRAINT
块之前的最后一个,
:
sed -r '/,/{N;/CONSTRAINT/{:a;N;/GO/!ba;s/([^,]+).*/1n)/};/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/([^,]+).*/1n)/
}
}
您可以将上面的多行脚本保存在一个文件中,并使用执行它
sed -rf script.sed input.sql
您可以使用以下sed
命令:
sed '/CONSTRAINT/{:a;N;/GO/!ba;s/.*/)/}' input.sql
该模式搜索包含/CONSTRAINT/
的行。如果找到该模式,则开始在{ }
之间封装一个命令块。在该块中,我们首先定义标签a
到:a
。我们通过N
获得下一行输入,并将其附加到模式缓冲区。除非我们找到模式/GO/!
,否则我们将使用分支命令b
继续标记a
。如果找到模式CCD_ 13,我们简单地用CCD_。
一个替代方案可以使用像FredPhil建议的范围:
sed '/CONSTRAINT/,/GO/{s/GO/)/;te;d;:e}'
这可能看起来很可怕,但通过一点解释就不难理解:
SED_DELIM=$(echo -en " 01")
START=' CONSTRAINT Index1 PRIMARY KEY CLUSTERED'
END='GO'
sed -n $'x5c'"${SED_DELIM}${START}${SED_DELIM},"$'x5c'"${SED_DELIM}${END}${SED_DELIM}{s${SED_DELIM}GO${SED_DELIM})${SED_DELIM};t a;d;:a;};p" test2.txt
sed有以下形式,您可能更熟悉:sed /regex1/,/regex2/{commands}
首先,它使用不可打印的SOH作为分隔符