Home > Back-end >  Remove YYYY_MM_DD_HH_MM from filename
Remove YYYY_MM_DD_HH_MM from filename

Time:12-24

We have few csv and xml files in following formats

String_YYYY_MM_DD_HH_MM.csv

String_YYYY_MM_DD_HH_MM.xml

String.xml

String.csv

Examples:

Reference_Categories_2021_02_24_17_14.csv
CD_CategoryTree_2021_02_24_17_14.csv
New_Categories.xml
Mobile_Footnote_2021_03_05_16_21.csv
Campaign_Version_2018_09_24_20_00.xml
Campaign_new.csv

Now we have to remove _YYYY_MM_DD_HH_MM from filenames so result will be

Reference_Categories.csv
CD_CategoryTree.csv
New_Categories.xml
Mobile_Footnote.csv
Campaign_Version.xml
Campaign_new.csv

Any idea how to do that in bash?

CodePudding user response:

In pure bash:

pat='_[0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9]_[0-9][0-9]_[0-9][0-9]'

for f in *$pat*; do echo mv "$f" "${f/$pat}"; done

Delete the echo if the output looks fine.

CodePudding user response:

You can use bash rename command for this solution.

Isolate all of your files into a directory, and then execute this command inside this directory:

rename 's/_[0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9]_[0-9][0-9]_[0-9][0-9]//g' /your/directory/*

[0-9] is a wildcard representing one number digit in the search string. In your case, _YYYY_MM_DD_HH_MM translates to this: _[0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9]_[0-9][0-9]_[0-9][0-9].

rename will search for this specific string with numbers/spacing in all filenames. Once the command finds these strings, it will rename these files while removing these strings on the fly.

CodePudding user response:

With bash Something like:

shopt -s nullglob

for f in *.{xml,csv}; do
  ext="${f##*.}"
  [[ "${f%%_[0-9]*}" = *.@(xml|csv) ]] && continue
  echo mv -v -- "$f" "${f%%_[0-9]*}.$ext"
done

With the =~ operator and BASH_REMATCH

shopt -s nullglob

regexp='^(.{1,})(_[[:digit:]]{4}_[[:digit:]]{2}_[[:digit:]]{2}_[[:digit:]]{2}_[[:digit:]]{2})([.].*)$'

for f in *.{xml,csv}; do
  [[ "$f" =~ $regexp ]] &&
  echo mv -v -- "$f" "${BASH_REMATCH[1]}${BASH_REMATCH[-1]}"
done

  • Remove the echo if you're satisfied with the output.
  •  Tags:  
  • bash
  • Related