1

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

2
  • I'm trying to understand your code. The code in file 1 looks suspicious. There isn't any language that I know of using that syntax. I'll assume that's the input. The code in File 2 looks like sql statements but the code before the select statement threw me off. Please reformat your code and I will debug your code and post a reply. Commented Jul 22, 2014 at 1:45
  • Hi @alvits, File 1 contain all the file names with .sh extension (instead of .txt) and File 2 will definitely have entry for all the file names give in File 1. Actually I missed a entry for BBB by mistake.. Commented Jul 22, 2014 at 14:18

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

The first file is useful to create the "missing" files, such as BBB.txt. Before the while loop, you can xargs touch < file1
0

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

1 Comment

better hope the content doesn't contain double spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.