5

I have files available in a directory as:

filename15_1
filename15_2
filename15_3
filename15_4

And so on.

I have another file that contains mapping information for how I want to rename the files. This is a CSV file.

filename15_1,filename30_6
filename15_2,filename30_7
filename15_3,filename60_3
filename15_4,filename60_4
filename15_5,filename60_5
filename15_6,filename60_6

I want to rename the four files by reading the above mapping. Mapping files is having more information than the actual files present in the directory.

My files should be renamed to the following.

filename30_6
filename30_7
filename60_3
filename60_4

How can I do this?

Note: I am a database-background person and have little knowledge in Unix.

4
  • It depends on the format your mapping file has; your best bet is probably to read the mapping into an associative array. Also, it's good form to at least try solving the problem yourself before asking us to provide code for you. – Tom Hunt Sep 15 '15 at 16:04
  • one more thing..mapping file will have more information like – user134306 Sep 15 '15 at 16:07
  • 1
    Please edit your question to provide the information. Comments are for commentary. – Tom Hunt Sep 15 '15 at 16:10
  • So, your mapping file has the original file, a comma, and the target name? Or is the comma not in your file? – terdon Sep 15 '15 at 16:12
7

If your mapping file is comma separated, you can do this:

while IFS=, read orig target; do
    mv "$orig" "$target"
done < mapping.txt
0
5

Well, a rather inane answer but:

sed -e 's/^/mv /' -e 's/,/ /' $mapping_file | sh 
5

a readable, concise approach would be awk's system function

awk -F',' 'system("mv " $1 " " $2)' mappingFile.csv

that will run a command on for each line of the input file


a rundown on the command

  • awk a unix util that's great for processing tabular data
  • -F',' the "Field separator" is a comma
  • system("mv " $1 " " $2) runs for each line of the input file
    • system(x) run x in a subshell
    • $1 and $2 refer to the first and second columns respectively
    • "mv " $1 " " $2 implicit concatenation builds the command
  • mappingFile.csv use this input file
0

With the help of above answers I modified the code in the following way and is working.

cd $SRCE
for file in *
do

while IFS="," read srce target
do
if [[ $file = $srce ]] ; then 
mv "$srce" "$target"
fi
done < map_lst
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.