Friday, October 03, 2008

Strip a Prepended String From a Filename - Unix

I had a process that was pre-pending by design its PID to a file name string. But unfortunately, it caused a few unexpected problems when this handling process inadvertently terminated. I had to rename the files without the defunct pre-pended PID string and then reprocess them (several thousand).

Here is what I used as a quick and dirty procedure.

# csh
# ls
prependPID_filename_etc1 prependPID_filename_etc2 prependPID_filename_etc3 prependPID_filename_etc4
# foreach filename (prependPID*)
? mv $filename `echo $filename | sed 's/prependPID_//'`
? end
# ls
filename_etc1 filename_etc2 filename_etc3 filename_etc4

# zsh
# ls
prependPID_filename_etc1 prependPID_filename_etc2 prependPID_filename_etc3 prependPID_filename_etc4
# for i in prependPID*
for> mv $i `echo $i | sed 's/prependPID_//'`
# ls
filename_etc1 filename_etc2 filename_etc3 filename_etc4