Creating a directory from a file name and moving bash

I have a file upload

BR0200.aaa.tsv BR0200.bbb.tsv BR0200.ccc.tsv BR0210.aaa.tsv BR0210.bbb.tsv BR0210.ccc.tsv W0210.aaa.tsv W0210.aaa.tsv W0210.aaa.tsv 

I would like to create a series of directories based on the first part of the file name, before the first "."

 BR0200 BR210 W0210 

and then move the related files to the correct directories (i.e. all BR0200. * files to the BR0200 directory).

I had a hit in a bash script, but I keep getting errors. Any advice would be greatly appreciated.

 #!/bin/bash for file in BR* W0*; do dir = "${file%%.*}" if [-e $dir];then mv "$file" "$dir" else mkdir -p "$dir" mv "$file" "$dir" fi done 

Sorry if this is the main question. I tried searching on the Internet, but with no result.

+6
source share
2 answers

No space around = allowed in an assignment.

 dir="${file%%.*}" 

Conversely, a space is required in the test.

 if [ -e $dir ]; then ^ ^ 

As for stylistic improvements, you don't need to make unnecessary mkdir -p , so you can get rid of the if .

Quotes are not required at the time of assignment, so you can remove them from the dir= . Quote is a good idea everywhere, but do not remove other quotation marks.

It might be useful to add an extra .* for loop. Thus, if you run the script more than once, it will not try to move these newly created subdirectories. And the neat trick (though not necessarily an improvement) is to reduce BR*.* W0*.* To {BR,W0}*.* .

 for file in {BR,W0}*.*; do dir=${file%%.*} mkdir -p "$dir" mv "$file" "$dir" done 
+6
source

You can try something like this:

 for file in BR* WO* do dir=$(echo ${file} | awk -F. '{print $1}' OFS=.) mkdir $dir mv $file $dir done 

I had a similar situation and it worked for me.

0
source

All Articles