Bash script rename multiple files

Let's say I have a bunch of files with a name something like this: bsdsa120226.nai bdeqa140223.nai, and I want to rename them to 120226.nai 140223.nai. How can I achieve this using the script below?

#!/bin/bash
name1=`ls *nai*`
names=`ls *nai*| grep -Po '(?<=.{5}).+'`
for i in $name1
    do
    for y in $names
        do
            mv $i $y
        done
    done



Solution:
name1=`ls *nai*`

for i in $name1
do
y=$(echo "$i" | grep -Po '(?<=.{5}).+')
mv $i $y
done
+4
source share
4 answers

Using only bash, you can do this:

for file in *nai* ; do
  echo mv -- "$file" "${file:5}"
done

(Remove echowhen it is satisfied with the exit.)

Avoid lsin scenarios other than displaying information. Use regular globbing instead.

See also How to perform string manipulations in bash? for stricter manipulation methods.


script : 5 , mv ( ), , .. lockstep. ( , .)

+1

:

#!/bin/bash

shopt -s extglob nullglob
for file in *+([[:digit:]]).nai; do
    echo mv -nv -- "$file" "${file##+([^[:digit:]])}"
done

echo, mv.

. , 5 . .

+2

rename (prename ), Perl :

prename 's/^.{5}//' *.nai

, script , , .

If you need to limit yourself to using this script, you need to work out one target file for each source file, for example:

#!/bin/bash
for i in *.nai; do
    y=$(echo "$i" | cut -c6-)
    mv "$i" "$y"
done
+1
source

If your system has a tool rename, it’s better to go to a simple command rename,

rename 's/^.{5}//' *.nai

It just removes the first 5 characters from the file name.

OR

for i in *.nai; do mv "$i" $(grep -oP '(?<=^.{5}).+' <<< "$i"); done
0
source

Source: https://habr.com/ru/post/1568518/


All Articles