Home > Enterprise >  Make a directory from a certain part of a file name using bash
Make a directory from a certain part of a file name using bash

Time:11-01

I have a file named assignment_UA_InleidingProgrammeren_Huistaak1-HelloWorld_2019-11-11.tgz

I need to make a directory InleidingProgrammeren and in this created directory I need to create another one called Huistaak1-HelloWorld using variables with bash. The directories names I have to get from the file name mentioned above

Note: I cannot use -mkdir InleidingProgrammeren/Huistaak1-HelloWorld

so it would look something like this

   -->assignment_UA_InleidingProgrammeren_Huistaak1-HelloWorld_2019-11-11.tgz
         -->InleidingProgrammeren 
               -->Huistaak1-HelloWorld

I have no idea how I have to do this. My teacher doesn't explain anything and just gives us crappy pdf files.

CodePudding user response:

You can use regular expressions here. A simple script for this would look something like this:

#!/bin/bash

folder1=$(echo assignment_UA_InleidingProgrammeren_Huistaak1-HelloWorld_2019-11-11.tgz | cut -f3 -d '_')
folder2=$(echo assignment_UA_InleidingProgrammeren_Huistaak1-HelloWorld_2019-11-11.tgz | cut -f4 -d '_')


mkdir -p "$folder1"/"$folder2"

I used echo here just as PoC. You should research regex and tools like grep, awk, sed, cut and so on.

  • Related