sed在特定的行号处用行内替换特定的列号值 [英] sed replace in-line a specific column number value at a specific line number
问题描述
我有一个5列的csv文件(以空格分隔):
I have a 5 columns csv file (space separated) like this :
username1 20130310 enabled 20130310 enabled
username2 20130310 enabled 20130321 disabled
username3 20130320 disabled 20130321 enabled
username4 20130310 disabled 20130310 disabled
我正在尝试更改username4
的第4列的值.
I'am trying to change the value of the 4th column for username4
.
我的脚本已经获取了行号和要存储的username4
的新值:所以我想用行号$lineNumber
的$newValue
替换第4列的值.
My script already gets the line number and the new value to store for username4
: so I would like to replace column 4 value with $newValue
at line number $lineNumber
.
在我的示例中:
newValue=anything
lineNumber=4
以便呈现:
username1 20130310 enabled 20130310 enabled
username2 20130310 enabled 20130321 disabled
username3 20130320 disabled 20130321 enabled
username4 20130310 disabled anything disabled
我计划使用sed
而不是awk
,因为使用sed
,我们可以使用-i
I plan to use sed
instead of awk
because with sed
we can do in-line changes with -i
推荐答案
这是一种方法:
$ sed '/^username4/{s/ [^ ]*/ anything/3}' file
username1 20130310 enabled 20130310 enabled
username2 20130310 enabled 20130321 disabled
username3 20130320 disabled 20130321 enabled
username4 20130310 disabled anything disabled
# store changes back to the file
$ sed -i '/^username4/{s/ [^ ]*/ anything/3}' file
但是避免使用awk
是不是很好的理由,因为sed
具有-i
选项. awk
更适合处理此类问题.
But avoiding awk
because sed
has the -i
option isn't a good reason. awk
is more suited to working with this kind of problem.
$ awk '$1=="username4"{$4="anything"}1' file
username1 20130310 enabled 20130310 enabled
username2 20130310 enabled 20130321 disabled
username3 20130320 disabled 20130321 enabled
username4 20130310 disabled anything disabled
# store changes back to the file
$ awk '$1=="username4"{$4="anything"}1' file > tmp && mv tmp file
使用awk
,您可以轻松地进行字段比较和编辑,使用shell变量并不是梦night以求的东西,而了解仅昨天编写的脚本不是问题,并且与sed
不同:
With awk
you can easily do field comparison and editing, using shell variable isn't a quoting nightmare and understanding scripts you wrote only yesterday isn't and issue unlike with sed
:
$ linenumber=4
$ newvalue=anything
$ awk 'NR==n{$4=a}1' n=$linenumber a=$newvalue file
username1 20130310 enabled 20130310 enabled
username2 20130310 enabled 20130321 disabled
username3 20130320 disabled 20130321 enabled
username4 20130310 disabled anything disabled
$ awk 'NR==n{$4=a}1' n=$linenumber a=$newvalue file > tmp && mv tmp file
这篇关于sed在特定的行号处用行内替换特定的列号值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!