在另一个文件中指定的值替换场 [英] Replace a field with values specified in another file

查看:106
本文介绍了在另一个文件中指定的值替换场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含词语之间的映射文件。我不得不提及该文件,并在一些文件映射的那些取代那些话。例如,下面的文件具有被映射像

I have a file that contains the map between the words. I have to refer to that file and replace those words with the mapped ones in some files. For example, below file has the table of words that are mapped like

1.12.2.4               1
1.12.2.7               12
1.12.2.2               5
1.12.2.4               4
1.12.2.6               67
1.12.2.12              5

我将有一个具有这些关键词(1.12.2。*)许多文件。我想搜索这些关键词,并从该文件中获取相应的映射替换那些话。如何做到这一点的外壳。假设一个文件包含以下行说。

I will have many files that has those key words (1.12.2.*). I want to search for these key words and replace those words with the corresponding mapping taken from this file. How to do this in shell. Suppose a file contains the following lines say

The Id of the customer is 1.12.2.12. He is from Grg. 
The Name of the machine is ASB
The id is 1.12.2.4. He is from Psg.

执行脚本后,数字1.12.2.12和1.12.2.4应该由5个和4(从主文件引用)所取代。谁能帮我?

After executing the script, the Numbers "1.12.2.12" and "1.12.2.4" should be replaced by 5 and 4 (referred from the master file). Can anyone help me out?

推荐答案

您可以有 SED SED 脚本为您提供:

You could have sed write a sed script for you:

的映射:

cat << EOF > mappings
1.12.2.4               1
1.12.2.7               12
1.12.2.2               5
1.12.2.4               4
1.12.2.6               67
1.12.2.12              5
EOF

输入文件:

cat << EOF > infile
The Id of the customer is 1.12.2.12. He is from Grg. 
The Name of the machine is ASB
The id is 1.12.2.4. He is from Psg.
EOF

生成基于映射脚本(GNU SED):

Generate a script based on the mappings (GNU sed):

sed -r -e 's:([^ ]*) +(.*):s/\1/\2/g:' mappings

输出:

s/\b1.12.2.4\b/1/g
s/\b1.12.2.7\b/12/g
s/\b1.12.2.2\b/5/g
s/\b1.12.2.4\b/4/g
s/\b1.12.2.6\b/67/g
s/\b1.12.2.12\b/5/g

与其他评估 SED (GNU SED):

sed -r -e 's:([^ ]*) +(.*):s/\\b\1\\b/\2/g:' mappings | sed -f - infile

输出:

The Id of the customer is 5. He is from Grg. 
The Name of the machine is ASB
The id is 1. He is from Psg.

请注意,该映射作为常规的前pressions,例如治疗一个点()意味着任何字符,并且可能需要转义无论是在映射文件或生成当 SED 脚本。

Note that the mappings are treated as regular expressions, e.g. a dot (.) can mean any character, and may need escaping either in the mappings file or when generating the sed script.

这篇关于在另一个文件中指定的值替换场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆