Xedrox
January 23, 2013, 2:57pm
1
Hi everyone,
I want to know, if there is a way to modify one line in a text file with unix script, with out re-writing all the file.
For example, i have this file:
CONFIGURATION_1=XXXX
CONFIGURATION_2=YYYY
CONFIGURATION_3=ZZZZ
supose i have a command or function "modify" that takes a file and modficates one line. "Modify" takes two arguments, the number of the line and the new value.
#script
modify 2 CONFIGURATION_2=XXXX
The result that i want on the file:
CONFIGURATION_1=XXXX
CONFIGURATION_2=XXXX
CONFIGURATION_3=ZZZZ
Thanks!
Sorry for my bad english.
Yoda
January 23, 2013, 3:13pm
2
line=$1
param=$2
awk -v L="$line" -v P="$param" 'NR==L{$0=P}1' file
Xedrox
January 23, 2013, 3:18pm
3
Nice! Supose other situation, the first parameter is nor the number of line, it is a string. For example:
CONFIGURATION_1=XXXX
CONFIGURATION_2=YYYY
CONFIGURATION_3=ZZZZ
supose i have a command or function "modify" that takes a file and modficates one line. "Modify" takes two arguments, a string and the new value. I want replace the line that contains a string "CONFIGURATION_2" with the value "CONFIGURATION_2=XXXX". Something like grep but writting.
#script
modify CONFIGURATION_2 CONFIGURATION_2=XXXX
The result that i want on the file:
CONFIGURATION_1=XXXX
CONFIGURATION_2=XXXX
CONFIGURATION_3=ZZZZ
Thanks!
Yoda
January 23, 2013, 3:22pm
4
param_1=$1
param_2=$2
awk -F= -v P1="$param_1" -v P2="$param_2" '$1==P1{$0=P2}1' file
Xedrox
January 24, 2013, 8:00am
5
Excelent! Thanks a lot!
---------- Post updated 01-24-13 at 08:00 AM ---------- Previous update was 01-23-13 at 03:53 PM ----------
One dude, it is posible modify the comand if the file = has space after or before, for examplo it is posible the file have this format:
PARAM1=XXXX
PARAM2 =AAAA
PARAM3 = BBBB
The comand just found with the first line.
Thanks!
Yoda
January 24, 2013, 12:06pm
6
Use awk gsub
function to truncate those extra spaces:
awk '{gsub(" ","")}1' file
Xedrox
January 24, 2013, 12:09pm
7
Where do i put this in the original command?
Yoda
January 24, 2013, 12:13pm
8
Here:
awk -F= -v P1="$param_1" -v P2="$param_2" '{gsub(" ","")}$1==P1{$0=P2}1' file
I hope this helps.