0

I have to call a SQL query from bash that outputs 1000 rows of two columns

  1. File_Path (Eg., /opt/files/dest/2.bin)
  2. Name_of_the_file (Eg., fax attachment.pdf, invoice.docx... yes, there are spaces).

The file name in the server file system is in different naming format eg: 1.bin, 22.bin. There are <1000 unique files exactly as some are missing.

Here is the Snapshot of the SQL query:

Select * from datafileinfo limit 4; 

Output:

FILEID,NAME 
/ran/file/MM/2012/04/3.bin,new_fax.pdf
/ran/file/MM/2013/06/12.bin,new_report.docx
/ran/file/MISC/2012/08/212.bin,daily_transact.jrxml
/ran/file/MONY/2013/04/122.bin,NULL

As a first step, I gathered all those files and put it in a temporary folder.

But I couldn't able to rename the files as I have to lookup the 'Name of the file' with corresponding 'File Path'. Is there any way I can perform the job?

  • Consider modifying your post to clean up the formatting so it is more easily readable. The first paragraph in particular is a little rough to understand. – HalosGhost Jan 1 '15 at 0:30
  • I can't figure out what you're asking. Can you show some sample rows of output, and what you want to do with it? – Barmar Jan 1 '15 at 0:41
  • This should be pretty simple to do with sed/awk, can you post a snippet of a SELECT query from the table so we can see the exact syntax. – Chris Davidson Jan 1 '15 at 8:20
  • Thanks! @HalosGhost for editing my post. I just added the snapshot of the SQL query above. – Chandra Jan 2 '15 at 3:44
  • @Chandra, what? – HalosGhost Jan 2 '15 at 3:55
0
  1. Change IFS separator to ","
  2. Iterate while loop over mysql query result
  3. Extract dir from old path
  4. Perform renaming

The code will be something like:

#!/bin/bash
IFS=','
mysql ...executequery... | while read oldpath newfname
do
  filedir=$(dirname $oldpath)
  mv "$oldpath" "$filedir/$newfname"
done

You didn't mention what to do with NULL query results.

  • Thanks @tomasz-myrta for providing the solution. The one with the NULL values I can name differently. I think that is straight forward. – Chandra Jan 3 '15 at 14:14

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.