Execute these commands as a root user
find var generated vendor pub/static pub/media app/etc -type f -exec chmod g+w {} +
find var generated vendor pub/static pub/media app/etc -type d -exec chmod g+ws {} +
Set the ownership to Magento user and web user using
sudo chown -R <Magento user>:<web server group> .
The error which you are facing is due to wrong ownership. If you navigate to the specified folder and run ll
you can find the ownership for the file is assigned to root user which is preventing from removing the generated files as Magento user.
Please at any case don't give 777 permission if so please revert it back.
Don't run any command as root user as it might cause the new static files to be created with root ownership which might prevent web user to access such files forcing you to provide 777 permission. So run Magento commands as Magento user.