Saturday, March 13, 2021

Dealing With Filenames Containing Spaces

Photo by XXSS IS BACK from Pexels

 

Since the Internet is used by a variety of users, operating systems and naming conventions it's not uncommon to get filenames that contain spaces.  Trouble is, this can wreak havoc with simple scripts that don't anticipate filenames with spaces.


for example;
With a folder containing files like this:
lipeltgm@kaylee:/var/tmp$ ls *ts
Nokomis Track - Minnebar15 - Oct 10th – Crowdcast-TohCuy6dhE00Y02iSoGYDo75LAQVfEmKmk (1).ts
Nokomis Track - Minnebar15 - Oct 10th – Crowdcast-TohCuy6dhE00Y02iSoGYDo75LAQVfEmKmk.ts
Nokomis Track - Minnebar15 - Oct 13th – Crowdcast-Qcgrm8WtcFKjmHYGs00Bg01Hy2HkkmmZYs.ts
Nokomis Track - Minnebar15 - Oct 6th – Crowdcast-OmLjaiEpTLslbQ9GHLmKITTSagJ00COuy.ts
Nokomis Track - Minnebar15 - Oct 8th – Crowdcast-JyWZ7lzwvH5MZSuGvp2uE49DVpeCVO3r.ts
Phalen Track Backup - Minnebar15 - Oct 13th – Crowdcast-dozLLcdmIlG6Bqdx2i99eNO8giYjpYsN.ts
Phalen Track - Minnebar15 - Oct 10th – Crowdcast-lzz9BX00V8cswvC2csSvecrjV00w1o80201G.ts
Phalen Track - Minnebar15 - Oct 13th – Crowdcast-vod_master.ts
Phalen Track - Minnebar15 - Oct 6th – Crowdcast-m7ItulACMOv6a6jhQuswa1nwseStEsfj.ts
Phalen Track - Minnebar15 - Oct 8th – Crowdcast-3xMlXLl8kVgTBVmbw602c78acyLDJpLcM.ts

A simple script, as follows, will interpret each entry as space/eol seperated.  Yes, you can address it by changing the delimiter, but another option is to simply rename the files to something more expected.

$ cat /tmp/go
for file in `find . -name "*.ts"`; do
echo $file
done

 The following find command will locate files with spaces in their names, changing the spaces to underscores ('_') to resemble something a bit easier to work with.

$ find . -type f -name "* *" | while read file; do mv "$file" ${file// /_}; done

Hope this helps.

No comments:

Post a Comment