| |||||||||||
Changing filenames in shell script Posted by hycheah (hycheah), 23 July 2007 Below are the filenames in my folder:filename1.doc filename2.xls filename3.ppt How do I change my filename to include an additional _dir1.? E.g. filename1_dir1.doc filename2_dir1.xls filename3_dir1.ppt What i can think of is like; > mv $filename $filename_dir1 But then the result would be filename1.doc_dir1 Posted by admin (Graham Ellis), 23 July 2007 Have a look at variable file name handling in the shell manual - it will let you use wach part of the file name on its own and you can rebuild the name in the way you want. It's shell dependent - so how exactly to do this will depend on which shell you have.Posted by george_Ball (george), 27 July 2007 Trymv foo.doc `basename foo.doc .doc`_dir1.doc Posted by hycheah (hycheah), 1 August 2007 I found out what shell i am using. It's Bourne shell.I am still stuck in this problem. The furthest i can get is splitting the filenames at the .ext, append _dir.ext at the filenames and store it in a text file. So my text file looks like: filename1_dir.txt filename2_dir.xls filename3_dir.ppt The problem now is how to perform the "mv" command to change the filenames. I don't want to hardcode my filenames in the shell script. Posted by admin (Graham Ellis), 2 August 2007 If you can pst up a same of code showing where and how you're holding the before and after names, I can probably come up with the appropriate copy command for you.Posted by hycheah (hycheah), 3 August 2007 Firstly i get all the filenames in the dir into files.txt> cat files.txt hss_tx.bat hss_tx.exe hss_tx.cpp Then i append the filenames in files.txt using: awk '{c=split($0, s, "."); print s[1]"_append."s[2] > "files2.txt"}' files.txt So files2.txt will look like: > cat files2.txt hss_tx_append.bat hss_tx_append.exe hss_tx_append.cpp Then i need to rename the filenames in files.txt to files2.txt e.g. (if hardcoded) mv hss_tx.bat hss_tx_append.bat At first i thought of reading the contents of files.txt and files2.txt into array1 and array2 respectively. Then maybe perform mv $array1[i] $array2[i] But since Bourne shell does not support array, i might have to re-work my script flow. Posted by admin (Graham Ellis), 3 August 2007 on 08/03/07 at 07:08:26, hycheah wrote:
Yes - if you modify the awk to produce ouput that includes both the old and mew names in each line (and puts a cp or mv in front of it), you'll be able to simply source that file to do the actual work. Quick and easy! Posted by hycheah (hycheah), 6 August 2007 Finally, after weeks of racking my brain, here is the answer:cat names.list | awk '{c=split($0, s, "."); print "mv "$0" "s[1]"_sim."s[2]""}' | sh This page is a thread posted to the opentalk forum
at www.opentalk.org.uk and
archived here for reference. To jump to the archive index please
follow this link.
|
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho |