Last active
February 27, 2024 03:08
-
-
Save amadanmath/1c488af92e3e50b8815efd50cc66560e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# https://stackoverflow.com/a/78062608/240443 | |
# Inspired by glenn jackman's awesome '$(NF-1) == "" {$(NF-1) = $NF} {NF--} 1' trick | |
file1=$1 | |
file2=$2 | |
key=${3:-name} | |
sep=${4:-|} | |
key1=$(head -1 "$file1" | awk -v FS="$sep" -v key="$key" '{ for (i = 1; i <= NF; i++) if ($i == key) print i }') | |
key2=$(head -1 "$file2" | awk -v FS="$sep" -v key="$key" '{ for (i = 1; i <= NF; i++) if ($i == key) print i }') | |
output=$( | |
awk -v FS="$sep" -v key="$key" ' | |
NR==1 { for (i = 1; i <= NF; i++) { p[$i] = i } } | |
NR!=1 { for (i = 1; i <= NF; i++) { if ($i != key && p[$i]) { o = o ",2." p[$i] } o = o ",1." i } print substr(o, 2) } | |
' <(head -1 "$file2") <(head -1 "$file1") | |
) | |
head -1 "$file1" && \ | |
join -t "$sep" -1 "$key1" -2 "$key2" -a 1 -o "$output" \ | |
<(tail -n +2 "$file1" | sort -t "$sep" -k 1,"$key1") \ | |
<(tail -n +2 "$file2" | sort -t "$sep" -k 2,"$key2") | \ | |
awk -F "$sep" -v OFS="$sep" '$(NF-1) == "" {$(NF-1) = $NF} {NF--} 1' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment