Replace AWK files using another file as a translation list

I am using awk on windows. I have a script called test.awk . This script should read the file and replace a certain amount (key) with a value. A list of key-> values ​​is located in a file called translate.txt .

The structure is as follows:

 e;Emil f;Friedrich g;Gustaf h;Heinrich i;Ida 

In a simple example, my input file will be

 e,111 f,222 g,333 h,444 i,555 .. 

therefore the output should be

 Emil,111 Friedrich,222 Gustaf,333 Heinrich,444 Ida,555 .. 

script I use the key2value user key2value to replace, but I am unable to pass this function to another translate.txt file as the source. See my code:

 { FS="," d=key2value($1) print d "," $2 } function key2value(b) { #this should use another file, not the currently processed one FILENAME="translate.txt" begin { FS=";" if ($1=b) { return $2 } end } 

Another thing is that FS does not work, it starts to work only from the second line.

+4
source share
2 answers

This simple single line line will do the trick:

 awk 'FNR==NR{a[$1]=$2;next}{print a[$1],$2}' FS=',|;' OFS=',' translate input Emil,111 Friedrich,222 Gustaf,333 Heinrich,444 Ida,555 

In the script form:

 BEGIN { # The BEGIN block is executed before the files are read FS="[,;]" # Set the FS to be either a comma or semi-colon OFS="," # Set the OFS (output field separator) to be a comma } FNR==NR { # FNR==NR only true when reading the first file key2value[$1]=$2; # Create associative array of key,value pairs next # Grab the next line in the first file } { # Now in the second file, print looked up value and $2 print key2value[$1],$2 } 

Run as:

 awk -f translate.awk translate.txt input.txt 

There are many errors with your script, you should read AWK Effective Programming .

+6
source

Code for GNU (Windows citation):

 sed -r "s#(\S+);(\S+)#/^\1,/s/.*,(\\S+)/\2,\\1/#" file1|sed -rf - file2 

Shell Session:

  > type file1 file2

 file1


 e; Emil
 f; Friedrich
 g; gustaf
 h; Heinrich
 i; Ida

 file2


 e, 111
 f, 222
 g, 333
 h, 444
 i, 555

 > sed -r "s # (\ S +); (\ S +) # / ^ \ 1, / s /.*, (\\ S +) / \ 2, \\ 1 / #" file1 | sed -rf - file2
 Emil 111
 Friedrich, 222
 Gustaf, 333
 Heinrich, 444
 Ida 555
+1
source

Source: https://habr.com/ru/post/1492266/


All Articles