Reputation: 305
I am trying to modify file name after fetching it from its path using basename in Ansible, I was successfully able to remove extension from name, but unable to achieve next target
Path: /bin/data/xyzzz_no_db_20.9.1-82.tgz
(i.e: xyzzz_no_db_20.9.1-82.tgz => xyzzzz_no_db_20.9.1-82 => xyzzz_no_db:20.9.1-82.(Final outcome expected)
Basically, need to replace last occurence of (_)(underscore) with (:)(coln), and tried same by using code mentioned below, their must be some modification required.
Thanks in Advance.
- name: Modify image name
set_fact:
imagename: " {{ latest_file.path | basename | regex_replace('.tgz', '') | regex_replace('/^[^_^_]*[0-9]/',':')}}"
Upvotes: 2
Views: 1174
Reputation: 626961
You may actually use a single regex for that:
(.*)_(.*)\.tgz$
Replace with \1:\2
. See the regex demo
In the code,
- name: Modify image name
set_fact:
imagename: " {{ latest_file.path | basename | regex_replace('(.*)_(.*)\\.tgz$', '\\1:\\2') }}"
Regex details
(.*)
- Group 1 (\1
): any zero or more chars other than line break chars, as many as possible_
- an underscore (not captured, we'll replace it with :
in the replacement pattern)(.*)
- Group 2 (\2
): any zero or more chars other than line break chars, as many as possible\.tgz
- .tgz
substring (note the .
is escaped to match a literal .
char)$
- end of string.Upvotes: 2