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; 



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, 2015 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, 2015 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. Jan 1, 2015 at 8:20
  • Thanks! @HalosGhost for editing my post. I just added the snapshot of the SQL query above.
    – Chandra
    Jan 2, 2015 at 3:44
  • @Chandra, what?
    – HalosGhost
    Jan 2, 2015 at 3:55

1 Answer 1

  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:

mysql ...executequery... | while read oldpath newfname
  filedir=$(dirname $oldpath)
  mv "$oldpath" "$filedir/$newfname"

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, 2015 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.