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;' )"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s