Search code examples
shellfinduglifycss

Change file extension while generating output file using uglifycss


I am using the uglifycss npm package to minify all the CSS files from the project output directory. I am executing the following post-build script to minify the CSS files content and rename the files by appending *.min.css

find dist/assets/css/ -type f -name "*.css" -exec uglifycss --output {}.min.css {} \; -exec rm {} \;

Files before executing the script:

enter image description here

Files after executing the script:

enter image description here

I want to remove existing .css from full filename path and append .min.css to it. I have tried several solutions but couldn't achieve the expected outcome. I have gone through the uglifycss docs but couldn't find anything. Is there a way I can trim the extension from {} file path?


Solution

  • The problem is with -exec, the {} is substituted with the complete filename and there is no direct way to remove the extension from {}. One way would be to use shell manipulation

    find dist/assets/css/ -type f -name "*.css" -exec sh -c '
        for file ; do
            uglifycss --output "${file%.css}.min.css" "$file"
            rm -- "$file"
        done
    ' _ {} +
    

    The trick is with parameter expansion ${file%.css}.min.css, the extension .css is removed and the part .min.css is added back.