简体   繁体   中英

How to rename a batch of files to a name that exists in the first line of each file

I need to rename a batch of files in a single directory to the characters between the backticks on the first row of the file contents.

File name: schema.stored.procedure302
First line in the file reads:

/* Procedure structure for procedure `usp_stored_procedure_abc` */

Desired new filename: usp_stored_procedure_abc.sql


Here's the scenario in a little more detail:

I have a single schema.sprocs.sql file that contains only the stores procedures from a mysqldump.

I used csplit to split the file into 300+ separate sql files

csplit -f schema.stored.procedure schema.sprocs.sql '/Procedure structure for procedure/' {*}

This worked brilliantly, and now I have files like this:

schema.stored.procedure302
schema.stored.procedure303
schema.stored.procedure304
etc...

What I need help with is:
What commands can I use to read the contents of each file, find the pattern:

/* Procedure structure for procedure `

Then rename the file with the characters that follow that pattern until a backtick is found.

For example:

The file schema.stored.procedure302 Contains the following line on the first row:

/* Procedure structure for procedure `usp_stored_procedure_abc` */

I need that file to be renamed to: usp_stored_procedure_abc.sql (the contents between the backticks on the first row of the file contents).

I'm sure this is feasible, can someone help me?

Following string shows, how we will get our new filename:

head -n 1 file |awk -F'[`]' '{print $2".sql"}'

Complete script would be this:

#!/bin/bash
for f in *;
do
  d="$(head -n 1 $f |awk -F'[`]' '{print $2".sql"}')" ;
  if [ ! -f "$d" ];
  then
    mv "$f" "$d"
  else echo "File '$d' already exists! Skiped!"
  fi
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM