LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Replace file name (https://www.linuxquestions.org/questions/programming-9/replace-file-name-4175520484/)

rohit_shinez 09-29-2014 09:29 AM

Replace file name
 
Hi,

I am having a files in my directory like this:

Code:

2014 1049_file1.txt
2014 1050_file2.txt
2014 1110_file3.txt
2014 1145_file4.txt
2014 2049_file5.txt

I need to replace the above file names like this without changing the content of filename:

Code:

file1.txt
file2.txt
file3.txt
file4.txt
file5.txt

I tried something like this but didn't workout:

Code:

for i in *.txt
do
mv $i ${*_i}
done


schneidz 09-29-2014 09:32 AM

since you have stupid spaces in your original filenames maybe you need to put quotes around them so that the shell can interpret them correctly (what is the error you are getting -- file not found ?) ?

there is prolly a better way but this is my quick-and-dirty hax with awk[untested]:
Code:

for i in *.txt
do
mv $i `echo $i | awk -F _ '{print $2}'`
done


rohit_shinez 09-29-2014 10:05 AM

Hi,

the above didn't work its giving error and moreover my code gave error like
-bash: ${*_i}: bad substitution

NevemTeve 09-29-2014 10:56 AM

Code:

for i in *.txt; do
    mv -- "$i" "${i#*_}"
done


teckk 09-29-2014 03:57 PM

My 2 cents

Another way to remove spaces in filenames in a folder
Code:

for i in *.txt; do mv "$i" ${i// /}; done
If those are all the same you also could remove the first 10 characters in the filenames.
Code:

for i in *.txt; do mv $i $(echo $i | sed 's .\{10\}  '); done
Or
Code:

for i in *.txt; do mv $i $(echo $i | cut -c 10-); done

suicidaleggroll 09-29-2014 04:57 PM

Quote:

Originally Posted by teckk (Post 5246505)
If those are all the same you also could remove the first 10 characters in the filenames.
Code:

for i in *.txt; do mv $i $(echo $i | sed 's .\{10\}  '); done
Or
Code:

for i in *.txt; do mv $i $(echo $i | cut -c 10-); done

or
Code:

for i in *.txt; do mv "$i" "${i:10}"; done

schneidz 09-30-2014 09:05 AM

Quote:

Originally Posted by rohit_shinez (Post 5246332)
Hi,

the above didn't work its giving error and moreover my code gave error like
-bash: ${*_i}: bad substitution

the only way to fix the error is to know what the error is ?


All times are GMT -5. The time now is 01:21 AM.