Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Bash one liner: remove extra slashes from file path

If you have a generated path, you might end up with extra slashes, such as

/mnt/foo//bar

In a typical Linux file system such as ext2, ext3, or ext4, /mnt/foo//bar is the same file as /mnt/foo/bar. The slashes two in a row are the same as a /./, and a single dot is the same directory. So /mnt/. is directory /mnt/ -- that's just how they made the filesystem. The notable exception is at the beginning of a path, where //servername would actually be a reference to the network host servername. I leave it as an exercise to the reader to know when he is parsing network paths and when he is not. You can clean duped slashes easily by doing this:

file="$( file | sed -e 's!\/\+!\/!g;' )"

Comments