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.