Vetri
Vetri

Reputation: 11

Create multiple files using FOR loop in Shell

I have 2 files. One contain list of the file names needs to be created and other file contain file name and the content(separated by tab) which I need to put it like below:

File 1:

AAA.txt   
BBB.txt  
CCC.txt  
DDD.txt

File 2:

AAA.txt  Select * from abc;  
AAA.txt  Delete from abc;  
CCC.txt  select * from xyz;  
DDD.txt  select * from efg;

Now I need to create File as AAA.txt (as in the File 1) and put the corresponding content which is in the File 2. Please note the no of lines for each file in File 2 may vary but it will be grouped by File name.

Thanks

Upvotes: 1

Views: 775

Answers (2)

jlliagre
jlliagre

Reputation: 30873

Here is one way in standard (POSIX) shell:

xargs touch < "File 1"
while read filename line; do
    printf "%s\n" "$line" >> $filename
done < "File 2"

Upvotes: 1

konsolebox
konsolebox

Reputation: 75618

Using awk:

awk -F'  ' 'NR == FNR { a[$1] = a[$1] $2 ORS } { t = $0; sub(/[[:blank:]]+$/, "", t) } t in a { printf "%s", a[t] > t }' file2 file1

Or safer even if data (on second column) has double spaces:

awk 'BEGIN { FS = OFS = "  " } NR == FNR { t = $1; $1 = ""; sub(/^[[:blank:]]+/, ""); a[t] = a[t] $0 ORS } { t = $0; sub(/[[:blank:]]+$/, "", t) } t in a { printf "%s", a[t] > t }' file2 file1

And using bash:

#!/bin/bash
FILE1=$1
FILE2=$2
[ -n "$BASH_VERSION" ] && [[ BASH_VERSINFO -ge 4 ]] || exit 1
shopt -s extglob
declare -A MAP=()
declare -A FLAGS=()
IFS=$' \t\n'  ## Use normal IFS.
while read -r LINE; do
    NAME=${LINE%%  *}
    DATA=${LINE#*  }
    MAP[$NAME]=${MAP[$NAME]}$DATA$'\n'
done < "$FILE2"
while read -r NAME; do
    (( ! FLAGS[$NAME]++ )) && : > "$NAME"
    echo -n "${MAP[$NAME]}" >> "$NAME"
done < "$FILE1"

Usage:

bash script.sh file1 file2

Upvotes: 0

Related Questions