[英]use sed awk to replace variable defined in another file
I have a users.txt file in the format: 我有一个格式为users.txt的文件:
User:CityID
Carl:0212
Syd:0312
Rick:9323
and a city.txt file in the format 以及格式为city.txt的文件
Anaheim:0212
San Jose:0312
I need to replace every CityID in the users.txt with the city name from the city.txt file. 我需要用city.txt文件中的城市名称替换users.txt中的每个CityID。 How can I achieve this using sed and awk?
如何使用sed和awk实现此目的?
I can get the column of CityID's using awk using: 我可以使用awk使用以下方法获取CityID的列:
awk -F$'\:' '{print $2}'< users.txt
but how do it replace them with the corresponding city name? 但是如何用相应的城市名称替换它们?
Thank you. 谢谢。
This would work: 这将工作:
awk 'BEGIN{FS=OFS=":"}NR==FNR{a[$2]=$1;next}{$2=a[$2]}1' city.txt user.txt
BEGIN{FS=OFS=":"}
: We set the Input and Output Field Separator to :
BEGIN{FS=OFS=":"}
:我们将输入和输出字段分隔符设置为:
NR==FNR{a[$2]=$1;next}
: We read the city file and create an array to store City Name indexed at City ID NR==FNR{a[$2]=$1;next}
:我们读取城市文件并创建一个数组来存储在城市ID处索引的城市名称
{$2=a[$2]}
: We replace the second field in user.txt by referencing the array {$2=a[$2]}
:我们通过引用数组替换user.txt中的第二个字段
1
: This is to print the line 1
:这是打印行
You can use sed
to transform city.txt
into a sed
script: 您可以使用
sed
将city.txt
转换为sed
脚本:
sed 's/\([^:]*\):\(.*\)/s%\2%\1%g/' city.txt
then feed that to a second sed
instance to process users.txt
: 然后将其提供给第二个
sed
实例以处理users.txt
:
sed 's/\([^:]*\):\(.*\)/s%\2%\1%g/' city.txt |
sed -f - users.txt
Not all sed
variants will accept a script file on standard input; 并非所有
sed
变体都将接受标准输入中的脚本文件。 you'll have to resort to a temporary file in that case. 在这种情况下,您将不得不求助于临时文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.