开发者

How to use regular expression in sed command

i have some strings with this pattern in some files:

  • domain.com/page-10
  • domain.com/page-15 ....

and i want to replace them with something like

  • domain.com/apple-10.html
  • domain.com/apple-15.html

i have found that i can use sed command to replace them at a time but because after the numbers should something be added i guess i have to use开发者_Go百科 regular expression to do it. but i don't know how.


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

Besides sed, you can also use gawk's gensub()

awk '{b=gensub(/page-([0-9]+)/,"apple-\\1.html","g",$0) ;print b  }' file


sed -i 's/page-\([0-9]*\)/apple-\1.html/' <filename>

The ([0-9]*) captures a group of digits; the \1 in the replacement string references that capture and adds it as part of the replacement string.

You may want to use something like -i.backup if you need to keep a copy of the file without the replacements, or just omit the -i and instead use the I/O redirection method instead.


One more way to resolve the problem:

sed -i.bak 's/\(^.*\)\(page-\)\(.*\)/\1apple-\3.html/' Files

Here the searching patterns are stored and retrieved using references (\1, \2, \3).


This will work

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜