Aidan Damerell
Aidan Damerell

Reputation: 21

Using an array to alter line delimited text file in bash

Not sure if this question has already been asked but basically I want to read from a file1 which contains special characters and alter them into a URL encoded version. file2 is a pipe delimited document such as: #|%23.

So when the script reads from the file1 a "#" it would change this to "%23". There are 174 different characters to recognise so if statements wouldn't be feasible.

Note: I am writing this is bash

I was considering using something like sed or awk however I don't know how I could use this with a text file.

Any suggestions?

Upvotes: 2

Views: 57

Answers (1)

NeronLeVelu
NeronLeVelu

Reputation: 10039

awk -F '|' '
   FNR == NR { Trsl[ $1 ] = $2; next}
   FNR != NR { 
      s0 = $0
      for( Char in Trsl) {
         Cnt = split( s0, a0, Char )
         s0 = a0[ 1 ]
         for( i = 2; i <= Cnt; i++) s0 = s0 Trsl[ Char] a0[ i]
         }
      print s0
     }
   ' File2 File1
  • order of file is important to read the translation file before the file to translate
  • assume | is not in the special character list
  • gsub cannot be used due to unexpected result on meta character
  • as @karakfa remark, order of translation (related to File2 entry) is not keep, so some unwanted result could occur if character are used in earlier translated result occur like -> %20 and after % -> Percent will give Percent20 for an original

Upvotes: 2

Related Questions