如果我在文件(somefile.txt)中有以下文本:
CREATE TABLE "table_name" (
"id" int(11) unsigned NOT NULL,
"some_field" varchar(10),
);
CREATE TABLE "another_table" (
"id" int(11) unsigned NOT NULL,
"some_other_field" varchar(10),
);
我想删除每个语句中最后一个尾随逗号,使其变为:
CREATE TABLE "table_name" (
"id" int(11) unsigned NOT NULL,
"some_field" varchar(10)
);
CREATE TABLE "another_table" (
"id" int(11) unsigned NOT NULL,
"some_other_field" varchar(10)
);
我已经使用了正则表达式\,$\n\)
,但我似乎无法让它与 一起使用sed
,这会抛出:
sed: -e expression #1, char 23: Unmatched ) or \)
当我使用时:
sed -i -e 's/\,$\n\)/)/g' somefile.txt
答案1
如果文件的语法像示例中那样无处不在,您可以使用
sed -i -n -e '1h;1!H;${g;s/\,\n);/\n);/g;p}' somefile.txt
解释:
1h # copy first line the hold buffer
1!H # not first line -> append to the hold buffer
${ # execute at the end
g # copy hold buffer back to pattern buffer
s/ ... / # multiline replacement in pattern buffer
p # print pattern buffer
}
(也可以看看http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/)
这样,整个文件就会在内存中读取、保存和修改,如果文件太大,则需要选择不同的方式。
答案2
sed 'N;s/,\n)/\n)/;P;D' file
或对于 GNU sed
sed -z 's/,\n)/\n)/g' file
或 awk
awk '
f{
if(!/);/)
print ","
else
print ""
f=0
}
/,$/{
sub(",$", "")
printf $0
f=1
next
}
1' file