Stack Overflow Asked by Brun on January 5, 2021
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
Answered by Cyrus on January 5, 2021
Use a regular expression that matches the entire part that you want to replace, e.g.,
sed "$lineNumber s/:[^:]+/:$pass/" users.txt
# ^^^^^^ = not : one or more times
Answered by webb on January 5, 2021
if you want shell variables to get expanded, use double quotes in sed command:
sed "$var1 s/:/:$var2/" file
Answered by Kent on January 5, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP