Search code examples
unixawkprintingterminalmkdir

awk: print multiple files, each file into a new folder. Folder name extracted from input file


I'm struggling to add mkdir into the awk line.

input.txt:

A1 B1
A2 B2
A3 B3

Aim: Print each line into a new file. Each new file should have the same name, e.g. 'file.txt'. Each new file should be printed into its own new folder. The folder name should be taken from the first field of the respective line in the input file. Resulting folder structure:

home
|__input.txt
|
|__A1
|  |__file.txt
|
|__A2
|  |__file.txt
|
|__A3
|  |__file.txt

My awk to create files with file names from the input:

$ awk '{F = $1".txt"} {print > F}' input.txt

My awk to create folders with folder names from the input:

$ awk '{print "mkdir "$1}' input.txt | sh

But how to combine these and create folders with folder names from the input but maintain the same file name 'file.txt'?


Solution

  • You are not really "adding mkdir into the awk line". You're piping awk's output to a shell. I think this is better done with a single shell script (you will need the shell anyway to invoke mkdir):

    input=input.txt
    newfile=file.txt
    while IFS= read -r line; do
        first="${line% *}"                #This means "the line up to first space"
        mkdir "$first"
        echo "$line" > "$first/$newfile"
    done < "$input"