Make a directory from a certain part of a file name using bash

Issue

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.

Solution

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.

Answered By – JBravo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published