Marco Falzone Marco Falzone - 3 months ago 10
Bash Question

Linux batch copy files into directories based on filename pattern

I have a list of almost 500 pdf files with the following filename structure:

XXXX-YYYY-MM-DD.pdf


where
XXXX
is a variable lenght numeric code (1 to 4 digits) always delimitated by "-", for example:

51-2016-08-22.pdf
776-2016-08-22.pdf
3881-2016-08-22.pdf
4-2016-08-22.pdf
2860-2016-08-22.pdf


The goal is to copy each file into its own directory, naming the directories like the pattern (ie: file 776-2016-08-22.pdf goes to directory 776). How can I use awk or sed to delimitate the variable lenght field?

Here's my code:

for f in *.pdf

do
FOLDERNAME=`echo $f| awk (awk or sed missing code here)`
mkdir /my/dir/structure/$FOLDERNAME
cp $f /my/dir/structure/$FOLDERNAME/
done


Thanks for your support.

Answer

awk -F '-' to specify delimiter and '{print $1}' for first element before delimiter.

for f in *.pdf

do
    FOLDERNAME=`echo $f| awk -F '-' '{print $1}'`
    mkdir /my/dir/structure/$FOLDERNAME
    cp $f /my/dir/structure/$FOLDERNAME/
done
Comments