Rename multiple files based on pattern in Unix

前端 未结 22 1136
死守一世寂寞
死守一世寂寞 2020-11-22 06:31

There are multiple files in a directory that begin with prefix fgh, for example:

fghfilea
fghfileb
fghfilec

I want to rename a

22条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 07:13

    There are many ways to do it (not all of these will work on all unixy systems):

    • ls | cut -c4- | xargs -I§ mv fgh§ jkl§

      The § may be replaced by anything you find convenient. You could do this with find -exec too but that behaves subtly different on many systems, so I usually avoid that

    • for f in fgh*; do mv "$f" "${f/fgh/jkl}";done

      Crude but effective as they say

    • rename 's/^fgh/jkl/' fgh*

      Real pretty, but rename is not present on BSD, which is the most common unix system afaik.

    • rename fgh jkl fgh*

    • ls | perl -ne 'chomp; next unless -e; $o = $_; s/fgh/jkl/; next if -e; rename $o, $_';

      If you insist on using Perl, but there is no rename on your system, you can use this monster.

    Some of those are a bit convoluted and the list is far from complete, but you will find what you want here for pretty much all unix systems.

提交回复
热议问题