I have two files say File A and File B. I want to merge the two files as shown below.
File A
Data A
a 123
b 35
-------
Data B
-------
Data C
a 234
d 23
File B
Data A
a 12
c 1
-------
Data B
-------
Data C
d 24
Output should be
Data A
a 135
b 35
c 1
-------
Data B
-------
Data C
a 234
d 47
Data A,Data ... will be in the same order for both the files and the variables under Data A, Data ... will also be alphabetically sorted for both the files but some variable may be there in one file or may not.
I tried to outer join the two files for every block (delimiter as ----) and then add the two numbers but i couldn't think of any way to do it.
Should be probably done in some real programming language but you asked for a bash so here it goes:
#!/bin/bash
declare -A data
read_sect_from_fd() {
local fd=$1
while read -u $fd -r var val; do
[[ $var == ------- ]] && break
if [ "${data[$var]}" ]; then
data[$var]=$(( $val + ${data[$var]} ))
else
data[$var]=$val
fi
done <&3
}
print_sect() {
for i in "${!data[@]}"; do
echo "$i ${data[$i]}"
done
}
exec 3<"File A"
exec 4<"File B"
while IFS= read -u 3 -r heading ; do
read_sect_from_fd 3
IFS= read -u 4 -r heading
read_sect_from_fd 4
[ "$not_first" ] && echo "-------"
not_first=1
echo "$heading"
print_sect
data=()
done
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.