Batch renaming files in command line and Xargs

后端 未结 9 739
余生分开走
余生分开走 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 17:22

    After some investigation on similar task here is my code:

    find . -maxdepth 1 -name '*.png' -print0 | sed 's/.png//g' | xargs -0 -I% -n 1 -P 8 convert -quality 100 %.png %.jpg
    

    Reasoning:

    • renaming will not compress the file (so use convert instead of mv)
    • ls \.png$ | xargs will not deal with spaces in the path/filename
    • find . will search in sub-folders, so use -maxdepth 1
    • convert doesn't use available CPUs so -P8 (or -P other)
    • sed without 'g' at the end will not substitute all files (only one)
    • sed 's/.png//g' will leave no extension (basename could also work but didn't after -print0)
    • parallel - potentially better solution but didn't work on my Ubuntu 18.04 bash 4.4
    • % is the smallest common symbol for substitution (compare to {} xx namePrefix)
    • -n2 parameter is good for xargs but didn't work with -print0 properly (n number of entries to take and pass after xargs)
    • -quality 100 default magic quality is 92 (which is fine), here 100% to avoid loosing anything

提交回复
热议问题