Awk 通过正则表达式查找文本并替换为查找表的最简单方法

Awk 通过正则表达式查找文本并替换为查找表的最简单方法,awk,replace,lookup-tables,Awk,Replace,Lookup Tables,遗留web应用程序需要国际化。错误消息当前以以下方式写入源代码中: addErrorMessage("some text here"); 使用正则表达式可以很容易地找到和提取这些符号。它们应该被这样的东西取代: addErrorMessage(ResourceBundle.getBundle("/Bundle", lcale).getString("key for text here")); 此处文本的键和此处某些文本之间的对应关系将在.property文件中 根据一些linux大师的说法,

遗留web应用程序需要国际化。错误消息当前以以下方式写入源代码中:

addErrorMessage("some text here");
使用正则表达式可以很容易地找到和提取这些符号。它们应该被这样的东西取代:

addErrorMessage(ResourceBundle.getBundle("/Bundle", lcale).getString("key for text here"));
此处文本的此处某些文本之间的对应关系将在.property文件中

根据一些linux大师的说法,它可以使用awk实现,但我对此一无所知。我可以编写一个小的应用程序来完成这项任务,但这可能有些过分。是否有ide插件或现有的应用程序来实现这一目标

awk -v TextOrg='some text here' -v key='key for text here' ' "addErrorMessage(\"" TextOrg "\")" {
   gsub( "addErrorMessage(\"" TextOrg "\")" \
       , "addErrorMessage(ResourceBundle.getBundle(\"/Bundle\", lcale).getString(\"" key "\"))")
   }
   7
   ' YourFile 
这是特定组合的一种方式。注意:

  • 赋值(
    -v…
    ,在这种情况下受shell解释的约束)
  • gsub正在使用正则表达式查找,因此您的文本需要使用此约束进行处理(例如:
    “this f***ing text”
    ->
    “this f\*\*\*ing text”
你当然想为几个同龄人做if

她用一个文件记录了她的同龄人

假设Trad.txt是一个包含一系列两行的文件,第一行是原始文本,第二行是键(以避免使用需要复杂转义序列解释的字符作为分隔符)

ex:Trad.txt

some text
key text
other text
other key
示例代码(简单,没有详尽的安全性,…)未经测试,但针对awk的概念

awk '
   # for first file only
   FNR == NR {
      # keep in memory first line as text to change
      if ( NR % 2 ) TextOrg = $0
       else {
          # load in array the key corresponding (index is the text to change)
          Key[ TextOrg] = $0
          Len[ TextOrg] = length( addErrorMessage(\"" $0 "\")"
          }
      # don't go further in script for this line
      next
      }

   # this point and further is reach only by second file 

   # if addError is found
   /addErrorMessage(".*")/{
      # try with each peer if there is a change (a more complex loop is more perfomant checking just necessary replacement but this one do the job)
      for( TextOrg in Key) {
         # to avoid regex interpretation
         # Assuming for this sample code that there is 1 replace (loop is needed normaly)
         # try a find of text (return the place where)
         Here = index( addErrorMessage(\"" TextOrg "\")", $0)
         if( Here > 0) { 
            # got a match, replace the substring be recreating a full one
            $0 = substr( $0, 1, Here) \
                 "addErrorMessage(ResourceBundle.getBundle(\"/Bundle\", lcale).getString(\"" Key[ TextOrg] "\"))") \
                 substr( $0, Here + Len[ TextOrg])
            }
      }           
   }

   # print the line in his current state (modified or not)
   7
   ' Trad.txt YourFile
最后,这是一个变通解决方案,因为可能会出现很多特殊情况,如
“ref:function addErrorMessage(\“…”)。bla bla“
将是一个问题,或者
()
中的空间未在此处处理,或者在die
()
中剪切线