Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sed替换为regex_Regex_File Io_Sed - Fatal编程技术网

Sed替换为regex

Sed替换为regex,regex,file-io,sed,Regex,File Io,Sed,我无法用简单的正则表达式替换sed。这是我面临的一个例子 我正在尝试替换文件中的行,如下所示: select * from mytable where mytable.s_id=274 select * from mytable where mytable.s_id=275 select * from mytable where mytable.s_id=276 select * from othertable where othertable.id=? select * from table3

我无法用简单的正则表达式替换sed。这是我面临的一个例子

我正在尝试替换文件中的行,如下所示:

select * from mytable where mytable.s_id=274
select * from mytable where mytable.s_id=275
select * from mytable where mytable.s_id=276
select * from othertable where othertable.id=?
select * from table3 where table3.name=?
为此:

select * from mytable where mytable.s_id=?
select * from mytable where mytable.s_id=?
select * from mytable where mytable.s_id=?
select * from othertable where othertable.id=?
select * from table3 where table3.name=?
我目前正在使用sed:

cat log | sed 's/where mytable\.s_id=[0-9]+/where mytable.s_id=/g' | sort
但是我在sed中使用的正则表达式(
's/where mytable\.s_id=[0-9]+/where mytable.s_id=/g'
)不能替代任何东西

我正在尽可能多地阅读文档,但我所阅读的一切都是不同的,有着不同的做事方式,所以我有点迷茫。使用sed替换正则表达式的标准方法是什么?在我的特殊情况下,它会是什么样子


注意:我简化了我面临的问题。我确实想使用sed(以便最终学会使用它),我确实想通过管道进行输入和输出(而不是就地编辑文件),因为我使用的命令行实际上比这更复杂。

好吧,一些sed不知道
+
。因此,请尝试以下方法:

 cat log | sed 's/where mytable\.s_id=[0-9]*/where mytable.s_id=?/g' | sort

编辑:
+
是一个GNU扩展,如果你使用它(你的sed知道它),你必须像choroba建议的那样转义它。

引用
+

sed 's/where mytable\.s_id=[0-9]\+/where mytable.s_id=?/g'

如果您对awk感兴趣,请在+前面加一个反斜杠。

awk -F= '{$2="=?";print}' temp
测试如下

> cat temp
select * from mytable where mytable.s_id=275
select * from mytable where mytable.s_id=276
select * from othertable where othertable.id=?
select * from table3 where table3.name=?
> awk -F= '{$2="=?";print}' temp
select * from mytable where mytable.s_id =?
select * from mytable where mytable.s_id =?
select * from othertable where othertable.id =?
select * from table3 where table3.name =?

.s和id之间是否有空格或下划线?您似乎在支持
+
的地方使用GNU-sed。您需要通过预加
\
来逃避它,或者使用扩展正则表达式开关
-r
运行
sed
。我想使用sed,我在问题中强调了这一点谢谢!为什么它需要逃跑?我觉得必须转义一个特殊字符很奇怪,而我不需要转义
[0-9]
。例如,我是否还需要转义
*
?是的,您需要将一些特殊字符转义为+事实上,这些字符被解释为正则表达式的规范。如果你想了解更多这方面的知识,请尝试在网上获取教程。
> cat temp
select * from mytable where mytable.s_id=275
select * from mytable where mytable.s_id=276
select * from othertable where othertable.id=?
select * from table3 where table3.name=?
> awk -F= '{$2="=?";print}' temp
select * from mytable where mytable.s_id =?
select * from mytable where mytable.s_id =?
select * from othertable where othertable.id =?
select * from table3 where table3.name =?