Showing posts with label rename. Show all posts
Showing posts with label rename. Show all posts

Tuesday, 13 April 2010

Perl One Liner: Remove whitespace from file name

It is often a pain to have spaces in file names when working at the command line, so remove them, or at least replace then with underscores. In this case it works on all bed files in the current directory.

ls *.bed |perl -ne 'use File::Copy;chomp;$old=$_;s/\s+/_/g;move($old,$_);'
You could replace the ls with a find for more control. 

Thursday, 5 November 2009

Perl one liner: Rename a file with some of its contents

I had some microarrays files that the scanner had named something not very useful. I wanted them renamed with their chip barcode which was in side the file.

perl -ne '`mv $ARGV $1.txt` if m/(1234567890(\d+_\d+_\d+))/;' *.txt

This little one liner does just that. The current file name is stored in $ARGV by default then I simply rename it from that to the extracted text I want.

Monday, 10 August 2009

One Liner: Remove File Extensions

Just a quick one, I downloaded the latest genome build already repeat masked but I the script I am running required the files to be just chromosome.fa (not chromosome.fa.masked). This quick bash one liner removes the masked part using basename.

for f in *.masked;do mv ${f} $(echo $(basename ${f} .masked));done

Friday, 7 August 2009

One Liner: Remove whitespace from filenames

Spaces in filenames can make all kinds of things break, it is good practice not to use them, but people do. So here is a good fix.

find . -type f -name "* *" -maxdepth 1| while read src; do mv "$src" `echo $src | tr " " "_"`; done

This script looks for all files in the current directory with a space in and moves them (which is how to rename things in unix) with spaces replaced by underscores. 

You could do the same with with perl too, which includes a check to stop overwriting of any existing files. 

find . -type f -maxdepth 1| perl -ne 'chomp; $o = $_; s/ /_/g; next if -e; rename $o, $_'; 

You could replace the find part with a simple ls but  this method makes it easy to change the -type f into a -type d to do the same thing on directories, or change the -maxdepth to work a a whole tree of directories.