1

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?

Inian
  • 80,270
  • 14
  • 142
  • 161
Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73

2 Answers2

3

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.

Inian
  • 80,270
  • 14
  • 142
  • 161
1

Found answer here and transform it to your needs like this

find dist/assets/css/ -type f -name "*.css" -exec bash -c 'name="{}"; uglifycss --output "${name//css/min.css}" "$name"' \; -exec rm {} \;
Ivan
  • 6,188
  • 1
  • 16
  • 23
  • 2
    This spawns a bash shell for each occurrence of the .css file found and might do the substitution incorrectly if the filename is for e.g. `cssmain.css` – Inian Aug 19 '20 at 12:16