Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regular expression in sed command

Tags:

regex

sed

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 regular expression to do it. but i don't know how.

like image 743
hd. Avatar asked Sep 17 '25 06:09

hd.


2 Answers

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
like image 140
ghostdog74 Avatar answered Sep 21 '25 08:09

ghostdog74


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.

like image 29
Amber Avatar answered Sep 21 '25 10:09

Amber