简体   繁体   中英

Perl one liner to increment a value and replace text

I have a line in some files where only the year differs -- I need to increment the year and replace the preceding text, for example:

tdef 12 linear 18Z31dec2012 1mo

should become:

tdef 12 linear 00Z01jan2013 1mo

I have a perl one liner that I can't get to replace the text and increment at the same time. I've tried quite a few combinations, the correct formatting evades me. This increments but of course I lose the text:

perl -pe 's/18Z31dec(\d+)/ 1 + $1 /ge'

I can't figure how to insert any text on the substitution and retain the incremented year:

perl -pe "s/18Z31dec(\d+)/'00Z01jan($1 + 1)'/ge"

Outputs this:

tdef 12 linear 00Z01jan( + 1) 1mo
perl -pe 's/18Z31dec(\d+)/"00Z01jan" . ($1 + 1)/ge'

When you use /e , the right side of the substitution is a full Perl expression. So you have to quote literal strings, concatenate them with . , etc.

Instead of concatenation, you could use the somewhat unattractive arbitrary-expression interpolation syntax that's based on scalar dereference:

perl -pe 's/18Z31dec(\d+)/"00Z01jan${\($1 + 1)}"/ge'

Same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM