#! /usr/bin/gawk -f BEGIN { abort = -1; usage = "fix-blanks-in-file-names < INFILE > OUTFILE"; # Reads a list of file pathnames that may include blanks. Outputs {mv} # commands that hopefully fix those names. } /./ { f = ("./" $0); while (match(f, /[ ]/)) { pref = substr(f, 1, RSTART); suff = substr(f, RSTART+1); if ((pref suff) != f) { printf "** 1 [%s] [%s] [%s]\n", f, pref, suff > "/dev/stderr"; exit(1); } match(pref, /[\/][^\/]*$/) dir = substr(pref, 1, RSTART) rest = substr(f, RSTART+1) if ((dir rest) != f) { printf "** 2 [%s] [%s] [%s]\n", f, dir, rest > "/dev/stderr"; exit(1); } old = rest; # Path element that contains the space. gsub(/[\/].*$/, "", old) if (old == rest) { rest = "" } else { gsub(/^[^\/]*/, "", rest); } if ((dir old rest) != f) { printf "** 3 [%s] [%s] [%s] [%s]\n", f, dir, old, rest > "/dev/stderr"; exit(1); } new = old; gsub(/[ ]/, "_", new); gsub(/^[_]+/, "", new); gsub(/[_]+$/, "", new); gsub(/[_][_]+/, "_", new); if (new == "") { new = "BLANK"; } if (old == new) { printf "** 4 [%s] [%s] [%s]\n", f, old, new > "/dev/stderr"; exit(1); } printf "( cd %s && mv -vi '%s' '%s' )\n", dir, old, new f = (dir new rest) } }