Pregunta

I have a lot of files (in single directory) like:

[a]File-. abc'.d -001[xxx].txt

so there are many spaces, apostrophes, brackets, and full stops. The only differences between them are numbers in place of 001, and letters in place of xxx. How to remove the middle part, so all that remains would be

[a]File-001[xxx].txt

I'd like an explanation how such code would work, so I could adapt it for other uses, and hopefully help answer others similar questions.

¿Fue útil?

Solución

Here is a simple script in pure bash:

for f in *; do            # for all entries in the current directory
  if [ -f "$f" ]; then    # if the entry is a regular file (i.e. not a directory)
    mv "$f" "${f/-*-/-}"  # rename it by removing everything between two dashes 
                          # and the dashes, and replace the removed part 
                          # with a single dash
  fi
done

The magic done in the "${f/-*-/-}" expression is described in the bash manual (the command is info bash) in the chapter 3.5.3 Shell Parameter Expansion

The * pattern in the first line of the script can be replaced with anything than can help to narrow the list of the filles you want to rename, e.g. *.txt, *File*.txt, etc.

Otros consejos

If you have the rename (aka prename) utility that's a part of Perl distribution, you could say:

rename -n 's/([^-]*-).*-(.*)/$1$2/' *.txt

to rename all txt files in your desired format. The -n above would not perform the actual rename, it'd only tell you what it would do had you not specified it. (In order to perform the actual rename, remove -n from the above command.)

For example, this would rename the file

[a]File-. abc'.d -001[xxx].txt

as

[a]File-001[xxx].txt

Regarding the explanation, this captures the part upto the first - into a group, and the part after the second (or last) one into another and combines those.

Read about Regular Expressions. If you have perl docs available on your system, saying perldoc perlre should help.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top