Wednesday, April 10, 2019

Linux: trim the extensions from the filenames for a batch of files


Trim the extension (e.g. .bak) of one file is simple, e.g.:

$ mv myfile01.txt.bak myfile01.txt

If we have hundreds of such files, nobody would want to run hundreds of the similar commands:

$ mv myfile02.txt.bak myfile02.txt
$ mv myfile03.txt.bak myfile03.txt
...

We can use sed instead:

$ ls *.bak | sed -e 's/\(.*\)\(\.bak\)/mv \1\2 \1/' | sh

The explanation of this command:
  1. "ls *.bak" gets the list of the filenames and feed them to sed.
  2. For each filename, sed changes it to "mv something.bak something"
  3. In the first part of the "s" command of sed, a pattern matches anything ended with .bak. It uses \( and \) to group the filename into 2 parts. The 1st group \(.*\) matches anything before .bak. The 2st group \(\.bak\) matches the exact string .bak.
  4. In the second part of the "s" command of sed (mv \1\2 \1), \1 and \2 are substituted with the 2 groups described above. So \1 refers to anything before .bak, and \2 refers to .bak.
  5. The output of sed will be "mv something.bak something" and it is passed to sh command to run.
  6. This will be done for all the files from 'ls *.bak'.

No comments:

 
Get This <