-8

您有一个字典 Dictionary.txt 和一个输入文件 inFile.txt。字典会告诉您可能的翻译。unix shell中类似问题的解决方案:用字典替换似乎在这里硬编码了我无法完全理解的东西。您可以提出比字典更好的替换技术,但 AWK/Sed 脚本应该能够读取多个文件,在最简单的情况下,只有一个字典文件和一个 infile。

如何用 AWK 或 Sed 优雅地用字典替换?


例子

字典.txt

1 one
2 two 
3 three
four fyra
five fem

inFile.txt

one 1 hello hallo 2 three hallo five five

来自命令的输出,我们追求类似的命令awk/sed {} Dictionary.txt inFile.txt

one one hello hallo two three hallo fem fem

专门选择替换但一对一替换不起作用的 AWK 示例。

awk 'BEGIN {
 lvl[1] = "one"
 lvl[2] = "two"
 lvl[3] = "three"
 # TODO: this does not work 
 # lvl[four] = "fyra"
 # lvl[five] = "fem"
 # lvl[one] = "one"
 # lvl["hello"] = "hello"
 # lvl[hallo] = "hallo"
 # lvl[three] = "three"
 }
NR == FNR {
  evt[$1] = $2; next
  }
{
   print $1, evt[$2], $3, $4, evt[$5], $6, $7, evt[$8], evt[$9]
   #TODO: this dos not work, eg. one-one mapping   
   #   print evt[$1], evt[$2], evt[$3], evt[$4], evt[$5], evt[$6], evt[$7], evt[$8], evt[$9]
  }' dictionary.txt infile.txt
4

4 回答 4

4
$ awk 'NR==FNR{map[$1]=$2;next} { for (i=1;i<=NF;i++) $i=($i in map ? map[$i] : $i) } 1' fileA fileB
one one hello hallo two three hallo fem fem

请注意,它将任何连续空白链压缩为单个空白字符。告诉我们这是否是一个问题。

于 2013-09-03T22:24:22.147 回答
4

如果你有 gnu sed,它支持脚本文件-f

`-f SCRIPT-FILE'
`--file=SCRIPT-FILE'
     Add the commands contained in the file SCRIPT-FILE to the set of
     commands to be run while processing the input.

例如,您可以在“c.sed”中写下您的替换,然后

sed -f c.sed file

示例c.sed

s/1/one/g
s/2/two/g
...

编辑

刚才您没有用 awk 标记问题,当然,awk 单行会更简单:(以您的示例)

awk '$1=$2' file

测试:

kent$  echo "1 one
2 two 
3 three
four fyra
five fem"|awk '$1=$2'
one one
two two
three three
fyra fyra
fem fem
于 2013-09-03T19:55:02.670 回答
3

编辑

这回答了原始帖子。没有回答多次编辑和重组的问题......最重要的是,我-1从问这个问题的 OP 那里得到了一个......该死的!

是的,在 awk 中要简单得多:

这会将两列都打印为第二列的值:

awk '{print $2, $2}' file

如果要先翻转第二列:

awk '{print $2, $1}' file
于 2013-09-03T20:10:12.040 回答
3

如果ReplaceLeftWithRight_where_you_do_not_replace_things.txt包含成对的字符串替换,第一列中出现的任何文本都应该被第二列替换,

1 one
2 two 
3 three
four fyra
five fem

那么这可以简单地表示为sed脚本。

s/1/one/g
s/2/two/g
s/3/three/g
s/four/fyra/g
s/five/fem/g

你可以简单地使用sed来创建这个sed脚本:

sed 's%.*%s/&/g%;s% %/%' ReplaceLeftWithRight_where_you_do_not_replace_things.txt

然后将其输出传递给第二个实例sed

sed 's%.*%s/&/%;s% %/%' ReplaceLeftWithRight_where_you_do_not_replace_things.txt |
sed -f - someFile_Where_You_Replace_Things.txt

替换文件中的所有匹配项someFile_Where_You_Replace_Things.txt并将输出打印到标准输出。

遗憾的是,并非所有sed方言都支持-f -从标准输入读取脚本的选项,但这至少在大多数 Linux 上应该可以工作。

抱歉,如果我误解了您的问题陈述。

于 2013-09-03T20:46:21.267 回答