TransWikia.com

How to rename files with a specific name structure?

Unix & Linux Asked by dsl on December 8, 2021

How to write a shell script to rename the file in linux?

Ex:

234-2020-08-06-12-13-14-abc_up.csv

is renamed to

234-abc_up-2020-08-06-12-13-14.csv

2 Answers

You could try sed for the filename transformation (the syntax implies GNU sed):

Example:

echo "234-2020-08-06-12-13-14-abc_up.csv" | sed -E 's/(.*)-([[:digit:]]{4}(-[[:digit:]]{2}){5})-([^.]+).csv/1-4-2.csv/'
234-abc_up-2020-08-06-12-13-14.csv

This will look for

  • "any string" (stored in "capture group" 1), followed by
  • a timestamp in YYYY-MM-DD-hh-mm-ss notation (i.e. 4 digits, and then 5 times "dash, followed by 2 digits"), stored in "capture group" 2, and then
  • "any string up to but excluding the first period encountered", stored in capture group 4.

It will replace this pattern with "capture group 1", "capture group 4", "capture group 2", followed by .csv, which should meet your requirements.

If your sed doesn't understand POSIX character classes, replace [[:digit:]] by [0-9].

So, a shell script might look like

#!/bin/bash

fname="$1"
newname="$(sed -E 's/(.*)-([[:digit:]]{4}(-[[:digit:]]{2}){5})-([^.]+).csv/1-4-2.csv/' <<< "$fname")"

mv "$fname" "$newname"

Make sure to test it first, by replacing the mv line with

echo "Would now execute 'mv $fname $newname'"

If you are not using bash, you will have to change the command-substitution to

newname="$(echo "$fname" | sed -E etc.)"

Answered by AdminBee on December 8, 2021

This shell script would do the job:

#!/bin/bash
old_filename=$1
IFS='-' read -r -a arr <<< $old_filename    # read dash-separated substrings into the array 'arr'
tmpsub=${arr[7]%.csv.gz}                    # extract 7th substring, stripping out the file extension
for i in $(seq 6 -1 1)                      # shifts right the substrings
do                                          # in the array by one 
    arr[$(($i+1))]=${arr[$i]}               # position, starting by 1
done
arr[1]=$tmpsub                              # set the substring 1 to the value of the previous 7th substring
new_filename=$(printf -- "-%s" "${arr[@]}") # join the substrings into a dash separated string
new_filename=${new_filename:1}".csv.gz"     # add the extension
mv $old_filename $new_filename              # rename the file

If you name it, e.g., rename_csv.sh, and make it executable with chmod, you can call it with just the original filename as input as follows:

./rename_csv.sh 234-2020-08-06-12-13-14-abc_up.csv.gz

It does not show any output, but it renames the file as it should.

Answered by Giuseppe Clemente on December 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP