Renaming the file names in a directory

Hi, I have about 60 files in a directory and need to rename those files. For example the file names are

i_can_phone_yymmdd.txt  (where yymmdd is the date. i.e 170420 etc)
i_usa_phone_1_yymmdd.txt
i_eng_phone_4_yymmdd.txt

The new file names should be

phone.txt
phone_1.txt
phone_4.txt

I am using the following command but it works only for i_can_phone-170420.txt. The command is

for file in `ls *.txt`
do
  echo 'The file name is ......' $file

  new_file=`echo ${file}|cut -f3 -d_`.txt

  echo 'The new file name is ......' $new_file
  mv ${file} $new_file
done;

With 15 posts under your belt, you should have figured out code tags by now. Select text and hit the code button, the button.

`ls *.txt` is redundant, for file in *.txt does the same thing more reliably since it will not be confused by spaces in filenames.

If I understand you I think this may work:

#!/bin/bash

# IFS is a special variable which controls splitting.
# Set it to _ and we can split on that string.
# But we will need to restore its original value later!
OLDIFS="$IFS"
IFS="_"

for file in *.txt
do
  echo 'The file name is ......' $file

  # Split on IFS and store in $1, $2, $3 variables.
  # $1="i", $2="can", $3="phone", $4="170420.txt"
  set -- $file 
  shift 3 # Remove "i", "can", "phone", leaving $1="170420.txt"

  new_file=$(printf "_%s" "$@") # new_file=_$1_$2_$3_...
  new_file="${new_file:1}" # Strip off leading _

  echo "The new file name is ...... $new_file"
  echo mv ${file} $new_file
done;

IFS="$OLDIFS"

Remove the echo from mv once you've tested and are sure this does what you want.

Hi.

There are utilities that can do much of the work for you:

Rename multiple files, groups of files

        1) rename -- Debian version and RedHat version differ, q.v.
           (try package util-linux:
           http://en.wikipedia.org/wiki/Util-linux)

        2) ren -- RedHat relatives

        3) renameutils -- package contains qmv, imv, icp, qcp, and deurlname

        4) mved -- (circa 2006; good as of 2015.05), perl
           http://raf.org/mved/
           (An earlier shell version may be available.)

        5) rename -- perl builtin library routine (DIY)

        6) mmv -- move/rename/copy/append/link multiple files by wildcard patterns

        7) gprename - batch rename using a GUI

        8) krename - batch rename using a GUI

Bet wishes ... cheers, drl

Try also

for FN in *.txt
  do TFN=${FN#?_*_}
     echo mv ${FN} ${TFN%_*}.txt
  done
mv i_can_phone_yymmdd.txt phone.txt
mv i_eng_phone_4_yymmdd.txt phone_4.txt
mv i_usa_phone_1_yymmdd.txt phone_1.txt

Remove the echo if happy with the resulting proposals.

Thanks a lot RudiC, your logic works. It has save a hell lot of time for me. Have a nice day.

Naveed