Madza Farias-Virgens
Madza Farias-Virgens

Reputation: 1061

Make folder from part of a filename, and move corresponding files there - bash scripting

In have two directories finch_data/filteredfirst/aligned with files

firstZBND1X.sam
firstZBND2V.sam
firstZBND3X.sam
firstZBND4X.sam
firstZBND5X.sam

and finch_data/filteredsec/aligned

secZBND1X.sam
secZBND2V.sam
secZBND3X.sam
secZBND4X.sam
secZBND5X.sam

I have created a folder finch_data/filteredsec/combined where I have moved all my first*.sam and sec*.sam files.

Now I need to create individual sub-folders using the file manes between the prefix first or sec and .sam. So, folders like:

ZBND1X
ZBND2V
ZBND3X
ZBND4X
ZBND5X

And then I would need to move the files with those name strings into those corresponding folder.

Anyone with a one line bash to do this?

This is the closer I got from other forums

find . -name "*.sam" -exec sh -c 'mkdir "${1%.*}" ; mv "$1" "${1%.*}" ' _ {} \;

Upvotes: 1

Views: 72

Answers (1)

randomir
randomir

Reputation: 18697

This will do it for the files prefixed with first (do it similarly for sec):

#!/bin/bash

prefix=first
for file in ${prefix}*; do
    base="${file%.sam}"
    dir="${base#$prefix}"
    mkdir -p "$dir"
    mv "$file" "$dir"
done

It's not a cute oneliner, but it readable. You can write it in one line if you wish, though.

We simply iterate over all files in current directory prefixed with $prefix, calculating the dir name by stripping the known extension and a known prefix, then creating the directory (if necessary, with -p we don't get warnings if dir already exists), and finally moving the file in the target dir. If you wish, you can here also rename the file into something different, perhaps drop the directory name from the filename, etc.

Upvotes: 3

Related Questions