Wipe /data/ but not /data/media/ through ADB shell or fastboot
Boot into your custom Recovery, mount the data partition either using command-line or via GUI, and choose any of the following method:

(Note that TWRP already has the option to clear /data without touching /data/media. It uses rm -rf commands1.)

Go Immune


Make /data/media immutable2 i.e. immune from any modification. You can do so by executing:

adb shell chattr +i /data/media


You can also use -R for recursive immunity, though it was not needed in my test case. 

You can see the immune attribute (i) in the output of 

adb shell lsattr /data/

Time to go berserk

adb shell rm -rf /data/*


All the files and their holding directories inside /data/ should now be purged except the ones inside media, for which you would get the error (non-critical) Permission denied for every file inside that directory.
Now revoke the immunity using

adb shell chattr -i /data/media


Use -R if you used it previously. 


If-Else

Manually pick each directory under /data and use rm -rf on it. Could be tiresome, so you may consider  Izzy's shell-fu

adb shell for dir in /data/*; do if [[ "$dir" = "/data/media" ]]; then continue; else rm -rf "$dir"; fi; done;


Replace rm -rf with echo for a dry run.

The command  picks up each file-path3 under /data, then  checks against whether the file-path is for media folder: if yes, then pass; else nuke the file.




1: TWRP FAQ: What is a data/media device? 
2: Wikipedia: chattr 
3: General overview of the Linux file system: Sorts of files