Home > Software engineering >  Redirect output to multiple files in for loop shell
Redirect output to multiple files in for loop shell

Time:12-16

I have a script that for each file in a directory do something with the awk command.

For that i use a for loop, but i'd want that each awk command running for a file redirect my output to a file. Like 1 source file -> 1 target file.

For the moment, my shell is setup like this :

#!/bin/bash

FILES="/home/yha/AG2R/*"

for f in $FILES 
do 
    echo "Processing $f file.."; 
    awk -F ';' '$1=="TABLE" && $3=="" {printf "01 %s.\n\n", $2; next} {sub(/CHAR/,"PIC X", $2);printf "   * %s.\n\n     05 %s %s.\n\n", $3, $1, $2;}' $f > temp.cpy
done

As you can see i redirect the output in "temp.cpy" but not only does he only give me the last file of the directory output even if he'd put all my files transformation in that file this is not what i want as i described it at the beginning.

CodePudding user response:

Make the output file depend on $f.

awk -F ';' '...' "$f" > "$f.cpy"

CodePudding user response:

awk can do this by itself:

awk -F ';' '
    FNR == 1 {
        printf "Processing %s file..\n", FILENAME
        output = FILENAME ".out"
    }
    $1 == "TABLE" && $3 == "" {
        printf "01 %s.\n\n", $2 > output
        next
    } 
    {
        sub(/CHAR/,"PIC X", $2)
        printf "   * %s.\n\n     05 %s %s.\n\n", $3, $1, $2 > output
    }
' /home/yha/AG2R/*
  • Related