如何在符号的第一次出现和它的第二次出现之间的特定行中替换文本 [英] How to replace text in a specific line between first appearence of a symbol and second appearence of it
问题描述
所以,假设我有一些像这样的文本文件:
aaaa:bbbb:cccc:ddddeeee:ffff:gggg:hhhhiiii:jjjj:kkkk:llll
,并且我需要一个命令,该命令使我能够替换可变行中第一和第二:
之间的内容.我设法做到了这一点,但显然只是在中间添加了文本:sed $ lineNumber's/:/:'$ pass'/'users.txt
aaaa:bbbb:cccc:ddddeeee:asd:gggg:hhhhiiii:jjjj:kkkk:llll
awk
的工作:
awk -v col ="2";-v行="2"-v sep =:"-v new ="asd"'BEGIN {FS = OFS = sep} NR == row {$ col = new} {print}'文件
或
awk'NR == row {$ col = new} 1'col ='2'row ='2'FS =':'OFS =':'new ='asd'文件
输出:
aaaa:bbbb:cccc:ddddeeee:asd:gggg:hhhhiiii:jjjj:kkkk:llll
请参阅: 8个强大的Awk内置变量– FS , OFS ,RS,ORS, NR ,NF,文件名,FNR
So, let's say I have some text file like this:
aaaa:bbbb:cccc:dddd
eeee:ffff:gggg:hhhh
iiii:jjjj:kkkk:llll
and I need a command that makes me able to replace what is in between the first and second :
in a variable line.
I managed to do something like this but it's obviously just adding the text in the middle: sed $lineNumber' s/:/:'$pass'/' users.txt
the result given by the command should be someting like this if I want to replace what is in between the first and second ":" of the second line with "asd"
aaaa:bbbb:cccc:dddd
eeee:asd:gggg:hhhh
iiii:jjjj:kkkk:llll
A job for awk
:
awk -v col="2" -v row="2" -v sep=":" -v new="asd" 'BEGIN{FS=OFS=sep} NR==row{$col=new} {print}' file
or
awk 'NR==row{$col=new}1' col='2' row='2' FS=':' OFS=':' new='asd' file
Output:
aaaa:bbbb:cccc:dddd eeee:asd:gggg:hhhh iiii:jjjj:kkkk:llll
See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR
这篇关于如何在符号的第一次出现和它的第二次出现之间的特定行中替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!