Batch renaming files in command line and Xargs

后端 未结 9 746
余生分开走
余生分开走 2020-12-12 16:32

So, I have the following structure:

.
..
a.png
b.png 
c.png

I ran a command to resize them

ls | xargs -I xx convert xx -res         


        
9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 17:11

    My solution is similar to many of the xarg solutions, and particularly similar to Schleis'.

    The difference here is a full regex manipulation with match references, and sed commands that properly ignore files that don't match so you don't need to prefilter your listing.

    This is also safe for files with spaces and shell meta.

    Change \2 in the replacement to any desired extension.

    ls |
    sed -nE 's/Rick\.and\.Morty\.(S03E[0-9]{2})\..*(\.[a-z0-9]{3})/"&" "Rick and Morty \1\2"/;T;p' |
    xargs -n 2 mv
    

    Explanation

    The -n arg tell's sed not to print anything by default, the T command says skip to the end of the script if the previous s command didn't do a replacement, the p command prints the pattern space (only hit if the s command matches).

    The & in the replacement is a reference to the contents of the original filename match.

    If we replace mv in the command with bash -c 'echo "run($#) $@"' bash then we can see the number of times mv would be called, and with parameter count and value:

    $ ls |
      sed -nE 's/Rick\.and\.Morty\.(S03E[0-9]{2})\..*(\.[a-z0-9]{3})/"&" "Rick and Morty \1\2"/;T;p' |
      xargs -n 2 bash -c 'echo "run($#) $@"' bash
    run(2) Rick.and.Morty.S03E02.720p.HDTV.x264-BATV.mkv Rick and Morty S03E02.mkv
    run(2) Rick.and.Morty.S03E03.720p.HDTV.x264-BATV.mkv Rick and Morty S03E03.mkv
    run(2) Rick.and.Morty.S03E04.720p.HDTV.x264-BATV.mkv Rick and Morty S03E04.mkv
    run(2) Rick.and.Morty.S03E05.HDTV.x264-BATV[ettv].mkv Rick and Morty S03E05.mkv
    run(2) Rick.and.Morty.S03E06.720p.HDTV.x264-BATV.mkv Rick and Morty S03E06.mkv
    run(2) Rick.and.Morty.S03E06.HDTV.x264-BATV.mkv Rick and Morty S03E06.mkv
    run(2) Rick.and.Morty.S03E07.720p.HDTV.x264-BATV[ettv].mkv Rick and Morty S03E07.mkv
    run(2) Rick.and.Morty.S03E08.720p.HDTV.x264-BATV.mkv Rick and Morty S03E08.mkv
    run(2) Rick.and.Morty.S03E09.720p.HDTV.x264-BATV.mkv Rick and Morty S03E09.mkv
    run(2) Rick.and.Morty.S03E10.720p.HDTV.x264-BATV.mkv Rick and Morty S03E10.mkv
    

提交回复
热议问题