Skip to content
Advertisement

Renaming files in a directory based on an instructions file

I have a directory that regroups a .sql file and multiple data files.

/home/barmar/test.dir
├── database.sql
├── table1.unl
├── table2.unl
├── table3.unl
├── table4.unl
├── table5.unl
└── table6.unl

The .sql file contains an unload instructions for every .unl file the issue I have is that the names of the .unl files are not the same as the instructions on .sql.

Usually the name should be TABLE_TABID.unl Im looking for a way to retreive the names from the .sql file and rename the .unl files correctly.

The .sql file contains multiple instructions here’s an example of the lines that contain the correct names.

{ unload file name = table1_89747.unl number of rows = 8376}

As you can see the only thing in common is the table name (table1) in the example

The expected result should be something like that:

/home/barmar/test.dir
├── database.sql
├── table1_89747.unl
├── table2_89765.unl
├── table3_89745.unl
├── table4_00047.unl
├── table5_00787.unl
└── table6_42538.unl

Advertisement

Answer

This sed line will generate commands to rename files like table1.unl to names like table1_89747.unl:

sed -n 's/.*name = ([^_]*)(_[^.]*.unl).*/mv '''1.unl''' '''12'''/p' <database.sql

Assumptions: spaces exist around the = sign, and the filename is of the form FOO_BAR.unl, i.e. the underscore character and the extension are always present.

Sample output:

$ echo '{ unload file name = table1_89747.unl number of rows = 8376}' | sed -n 's/.*name = ([^_]*)(_[^.]*.unl).*/mv '''1.unl''' '''12'''/p'
mv 'table1.unl' 'table1_89747.unl'

To generate and execute the commands:

eval $(sed -n 's/.*name = ([^_]*)(_[^.]*.unl).*/mv '''1.unl''' '''12''';/p' <database.sql | tr -d 'n')

Goes without saying, before running this make sure your database.sql doesn’t have malicious strings that could lead to renaming files outside the current directory.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement