Replacing strings in file, using patterns from another file

女生的网名这么多〃 提交于 2019-12-11 07:29:40

问题


I need to replace many strings in many files using another file with patterns (like a database of strings). It is for anonymizing files.

Example:

File #1:

"Administrator";"512";"Built-in account for administering the computer/domain";"False";"False";"Administrator";"True";"True";"True";"S-1-5-21-3445027559-693823181-3401817782-500";"User";"OK";"23. 1. 2012 9:41:34";"20. 1. 2012 16:01:33";"10";"True";*

File #2 (the pattern file):

Guest;user1

Administrator;user2

system;user3

The output in File #1 needs to be

"user2";"512";"Built-in account for administering the computer/domain";"False";"False";"user2";"True";"True";"True";"S-1-5-21-3445027559-693823181-3401817782-500";"User";"OK";"23. 1. 2012 9:41:34";"20. 1. 2012 16:01:33";"10";"True";

Because the content of File #1 is variable, using some regex did not work in my case. I tried to use grep for finding, but it did not work either.


So far i tried this one

find file1.txt -type f -exec sed -f patt.regular {} \;

patt.regular is like this:

s/10.30.8.204/XX.YY.8.204/g

Unfortunately it does not work, I have suspicious, That source file format file1.txt have some issues, becouse nothing gonna happens, but when i delete original file (file1.txt) and create new one, it seems to be ok

Is there a possibility that sed could have some format trouble?


回答1:


In the shell,

for line in $(cat file2.txt); do sed -i "s/$(echo $line | cut -d ';' -f 1)/$(echo $line | cut -d ';' -f 2)/g" file1.txt; done

does what you want. It needs the files to be called file1.txt and file2.txt and to reside in the current directory.

This does a sed for each line in file2.txt.



来源:https://stackoverflow.com/questions/30163088/replacing-strings-in-file-using-patterns-from-another-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!