简体   繁体   English

如何仅在特定行和特定列中使用 awk

[英]How to awk only in a certain row and specific column

For example i have the following file:例如我有以下文件:

4:Oscar:Ferk:Florida
14:Steven:Pain:Texas
7:Maya:Ross:California

and so on... It has an unknown number of lines because you can keep adding more to it.等等...它的行数未知,因为您可以继续添加更多行。 I'm writing a script where you can edit the name by giving in the id of the person and the new name you want to give it as parameters.我正在编写一个脚本,您可以在其中通过输入人员的 id 和要为其提供的新名称作为参数来编辑名称。

What i am trying to do is use awk to find the line and then change the name on that specific line and update the file.我想要做的是使用 awk 找到该行,然后更改该特定行上的名称并更新文件。 I'm having trouble because my code updates every single column value to the given one.我遇到了麻烦,因为我的代码将每一列值更新为给定的值。

My current code is:我目前的代码是:

getID=$1
getName=$2

awk -v varID="$getID" -F':' '$0~varID' file.dat | awk -v varName="$getName" -F':' '$2=varName' file.dat > tmp && mv tmp file.dat

Help is really appreciated, thank you kindly in advance.非常感谢您的帮助,在此先感谢您。

You may use this awk:你可以使用这个 awk:

getID=14          # change to getID="$1"
getName='John K'  # change to getName="$2"

awk -v id="$getID" -v name="$getName" 'BEGIN{FS=OFS=":"} $1==id{$2=name} 1' file

4:Oscar:Ferk:Florida
14:John K:Pain:Texas
7:Maya:Ross:California

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM