[英]How can I replace lines in a text file with lines from another file based on matching key fields?
input.txt input.txt中
1,Ram,Fail
2,John,Fail
3,Ron,Success
param.txt (New Input) param.txt(新输入)
1,Sam,Success
2,John,Sucess
Now i want to replace the whole line in input.txt with those present in param.txt . 现在我想将input.txt中的整行替换为param.txt中的整行。 1st column will act like a primary key.
第一列将充当主键。
Output.txt Output.txt的
1,Sam,Success
2,John,Sucess
3,Ron,Success
I tried as 我试过了
awk 'FNR==NR{a[$1]=$2 FS $3;next}{ print $0, a[$1]}' input.txt param.txt > Output.txt
But it is merging the file contents. 但它正在合并文件内容。
This might work for you (GNU sed): 这可能适合你(GNU sed):
sed 's|^\([^,]*,\).*|/^\1/c\\&|' param.txt | sed -f - input.txt
Explanation: 说明:
param.txt
into a sed
script using the first field as an address to change the line in the input.txt
. param.txt
转换为sed
脚本作为地址来更改input.txt
的行。 s|^\\([^,]*,\\).*|/^\\1/c\\\\&|
input.txt
. input.txt
运行脚本。 sed -f - input.txt
This can be done with one call to sort
: 这可以用一个调用完成
sort
:
sort -t, -k1,1n -us param.txt input.txt
Use a stable numerical sort on the first comma-delimited field, and list param.txt
before input.txt
so that the correct, newer, lines are preferred when eliminating duplicates. 在第一个以逗号分隔的字段上使用稳定的数字排序,并在
input.txt
之前列出param.txt
,以便在删除重复项时首选正确的新行。
You could use join(1) to make this work: 您可以使用join(1)来完成这项工作:
$ join -t, -a1 -j1 Input.txt param.txt | sed -E 's/,.*?,.*?(,.*?,.*?)/\1/'
1,Sam,Success
2,John,Sucess
3,Ron,Success
sed as a pipe tail strips fields from Input.txt out of replaced lines. sed作为管道尾部从Input.txt中删除替换行中的字段。
This will work only if both input files are sorted by first field. 仅当两个输入文件都按第一个字段排序时,这才有效。
Pure awk isn't really the right tool for the job. 纯awk并不是真正适合这项工作的工具。 If you must use only awk, https://stackoverflow.com/a/5467806/1301972 is a good starting point for your efforts.
如果您必须只使用awk, https://stackoverflow.com/a/5467806/1301972是您努力的良好起点。
However, Unix provides some tools that will help with feeding awk the right input for what you're trying to do. 但是,Unix提供了一些工具,可以帮助您为正在尝试的操作提供正确的输入。
$ join -a1 -t, <(sort -n input.txt) <(sort -n param.txt) |
awk -F, 'NF > 3 {print $1 "," $4 "," $5; next}; {print}'
Basically, you're feeding awk a single file with the lines joined on the keys from input.txt. 基本上,你在awk中输入一个文件,其中的行连接在input.txt的键上。 Then awk can parse out the fields you want for proper display or for redirection to your output file.
然后awk可以解析出你想要正确显示的字段或重定向到输出文件。
This should work in awk
这应该在
awk
工作
awk -F"," 'NR==FNR{a[$1]=$0;next} ($1 in a){ print a[$1]; next}1' param.txt input.txt
$ cat input.txt
1,Ram,Fail
2,John,Fail
3,Ron,Success
$ cat param.txt
1,Sam,Success
2,John,Sucess
$ awk -F"," 'NR==FNR{a[$1]=$0;next} ($1 in a){ print a[$1]; next}1' param.txt input.txt
1,Sam,Success
2,John,Sucess
3,Ron,Success
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.