0

I have a list like this

G1 John
G2 Jack
G3 Ray
G4 Tim

and a second list in another file

Jack John
Tim Jack

I want to write a bash code that gives me a third file like this

G2 G1
G4 G2

EDIT My solution is this, but nothing happens when I write it in bash.

#! /bin/bash
INPUTFILE="id.tsv"
DATAFILE="g.tsv"
OUTFILE="output.csv"

awk 'BEGIN {
while (getline < "'"$INPUTFILE"'")
{
split($0,ft,"\t");
id=ft[1];
name=ft[2];

key=id;
data=name;
nameArr[key]=data;
}
close("'"$INPUTFILE"'");

while (getline < "'"$DATAFILE"'")
{
split($0,ft,",");
id1=ft[1]; # Id is the first column
id2=ft[2]; # Phonenumber is the second
name1=nameArr[id1]; 
name2=nameArr[id2]; 
print name1","name2 > "'"$OUTFILE"'"; # Print directly to the outputfile
}
}'
1
  • 3
    Use awk. Make an array using the keys and values in the first file, then loop through all the fields in the second file and make the substitutions. Try that and let us know if you get stuck. Commented Mar 23, 2016 at 16:33

2 Answers 2

2

awk to the rescue!

$ awk 'NR==FNR{a[$2]=$1; next} {print a[$1], a[$2]}' file1 file2

G2 G1
G4 G2
Sign up to request clarification or add additional context in comments.

Comments

1

Karakfa's answer using awk is very concise, and for that reason, I'd probably prefer that method in my own scripts.

However, it's worth noting that you can do this directly in bash (version 4 and above) using an associative array:

declare -A map

while read -r line; do
  id="${line% *}"
  name="${line#* }"
  map["$name"]="$id"
done < file1

while read -r line; do
  ids=()
  for name in $line; do
    ids+=( "${map["$name"]}" )
  done
  echo "${ids[@]}"
done < file2

Output:

G2 G1
G4 G2

Keep in mind that this code is not portable. If portability is a concern, that's even more reason to use awk instead.

Comments

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.