简体   繁体   中英

SED: replace semvers of multiple files

[ context ] My script needs to replace semvers of multiple .car names with commit sha . In short, I would like that every dev_CA_1.0.0.car became dev_CA_6a8zt5d832.car

ADDING commit sha right before .car was pretty trivial. With this, I end up with dev_CA_1.0.0_6a8zt5d832.car

find . -depth -name "*.car" -exec sh -c 'f="{}"; \
mv -- "$f" $(echo $f | sed -e 's/.car/_${CI_COMMIT_SHORT_SHA}.car/g')' \;

But I find it incredibly difficult to REPLACE . What aspect of sed am I misconceiving trying this:

find . -depth -name "*.car" -exec sh -c 'f="{}"; \
mv -- "$f" $(echo $f | sed -r -E 's/[0-9\.]+.car/${CI_COMMIT_SHORT_SHA}.car/g')

or this

find . -depth -name "*.car" -exec sh -c 'f="{}"; \
mv -- "$f" $(echo $f | sed -r -E 's/^(.*_)[0-9\.]+\.car/\1${CI_COMMIT_SHORT_SHA}\.car/g')' \;
no matches found: f="{}"; mv -- "$f" $(echo $f | sed -r -E ^(.*_)[0-9.]+.car/1684981321531.car/g)

or multiple variants:

  • \ escaping (eg \\. )
  • ( and ) escaping (eg \( ) (I read somewhere that regex grouping with sed requires some care with () )

Is there a more direct way to do it?

Edit

$f getting in sed are path looking like

./somewhere/some_project_CA_1.2.3.car
./somewhere_else/other_project_CE_9.2.3.car

You may use

sed "s/_[0-9.]\{1,\}\.car$/_${CI_COMMIT_SHORT_SHA}.car/g"

See the online demo

Here, sed is used with a POSIX ERE expression, that matches

  • _ - an underscore
  • [0-9.]\{1,\} - 1 or more digits or dots
  • \.car - .car (note that a literal . must be escaped! a . pattern matches any char)
  • $ - end of string.

Can you try this:

export CI_COMMIT_SHORT_SHA=6a8zt5d832
find . -depth -name "*.car" -exec sh -c \
 'f="{}"; echo mv "$f" "${f%_*}_${CI_COMMIT_SHORT_SHA}.car"' \;

Remove echo once you are satisfied of the 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