karlncreate
karlncreate

Reputation: 65

regex | how to add prefix to a matched substring?

Suppose I have the follow files:

../dir
   |__ attention.md
   |__ attention.percent.20.pt.md
   |__ attention.percent.60.st.md
   |__ attention.reserved.md

I want to add a [tag] to any files whose names contain percent, but apparently the code below replaces an entire prefix up to and including percent.

$ rename -n 's/(\w+\.)*(percent)(\w+\.)*/[tag]/' *.md

rename(attention.percent.20.pt.md, [tag].20.pt.md)
rename(attention.percent.60.st.md, [tag].60.st.md)

I should clarify my question:

I want to add [tag] to the beginning of any string that contains percent anywhere in the middle.

Upvotes: 1

Views: 180

Answers (1)

anubhava
anubhava

Reputation: 784898

You may use $& in replacement:

rename -n 's/(\w+\.)*percent(\w+\.)*/[tag]$&/' *.md
'attention.percent.20.pt.md' would be renamed to '[tag]attention.percent.20.pt.md'

$& is back-reference for complete matched text.

Alternatively you can just put your pattern in a lookahead as well:

rename -n 's/(?=(\w+\.)*percent)/[tag]/' *.md
'attention.percent.20.pt.md' would be renamed to '[tag]attention.percent.20.pt.md'

Upvotes: 1

Related Questions