Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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
Regex 如何在sed命令中使用正则表达式_Regex_Sed - Fatal编程技术网

Regex 如何在sed命令中使用正则表达式

Regex 如何在sed命令中使用正则表达式,regex,sed,Regex,Sed,我在一些文件中有一些具有此模式的字符串: domain.com/page-10 domain.com/page-15 我想用类似的东西来代替它们 domain.com/apple-10.html domain.com/apple-15.html 我发现我可以使用sed命令一次替换它们,但是因为在数字之后应该添加一些东西,我想我必须使用正则表达式来完成。但是我不知道怎么做。sed-i的/page-\([0-9]*\)/apple-\1.html/' sed -i 's/page-\([0

我在一些文件中有一些具有此模式的字符串:

  • domain.com/page-10
  • domain.com/page-15
我想用类似的东西来代替它们

  • domain.com/apple-10.html
  • domain.com/apple-15.html
我发现我可以使用sed命令一次替换它们,但是因为在数字之后应该添加一些东西,我想我必须使用正则表达式来完成。但是我不知道怎么做。

sed-i的/page-\([0-9]*\)/apple-\1.html/'
sed -i 's/page-\([0-9]*\)/apple-\1.html/' <filename>
([0-9]*)
捕获一组数字;替换字符串中的
\1
引用捕获并将其添加为替换字符串的一部分

如果需要保留文件的副本而不进行替换,则可能需要使用类似于
-i.backup
的方法,或者只需省略-i而改用i/O重定向方法

sed -i.bak -r 's/page-([0-9]+)/apple-\1.html/' file

sed  's/page-\([0-9][0-9]*\)/apple-\1.html/' file > t && mv t file
除了sed,您还可以使用gawk的
gensub()


解决此问题的另一种方法是:

sed -i.bak 's/\(^.*\)\(page-\)\(.*\)/\1apple-\3.html/' Files
这里使用引用(
\1
\2
\3
)存储和检索搜索模式。

这将起作用

sed 's/$/\.html/g' file.txt

您没有看到OP想要的全部内容。使用GNU Sed扩展-可以用标准Sed编写,将“+”替换为“[0-9]*”。@jonathan,您确定吗<代码>*为零或更多<代码>+是一个或多个<代码>[0-9][0-9]*应该更合适。是的,所以当我说的“+”被替换时,你会得到“[0-9][0-9]*”,这是一个或多个数字,正如你说的,这是合适的(我同意)。您没有指定如何使用\d+谢谢,但我运行了您给定的命令,并出现以下错误:`s'命令的RHST上的引用无效\1,这是因为您应该转义大括号…请参阅我的第2页answer@ghostdog74谢谢你回复我关于脱掉牙套的问题。我不知道我是否能自己解决这个问题sed's/$/\.html/g'file.txt
sed 's/$/\.html/g' file.txt