Reputation: 645
When any field is assigned to in AWK, $0
is recomputed and the original field separators are replaced with the output field separator (OFS
). But I want the field separators in $0
to remain unchanged when I change the fields. My input field separator (FS
) is a regular expression, so simply making the output file separator the same as the input file separator won't do.
Is there any way to change the fields without changing the field separators in $0
?
EDIT:
My input field separator is FS = "([^[:digit:]\\.,]|^)+0*[\\.,]?0*";
.
My script inspects the numbers on the left side of the equals sign and changes the numbers on right side accordingly for each line of input (to be exact, it finds and corrects the number of significant figures). For instance, given the input
50g * 10 = 500g
0.030L+1.12L=1.150L
my script should output
50g * 10 = 50E+1g
0.030L+1.12L=1.2L
, but due to the original field separators being replaced as I change the field that is the number on the right side of the equals sign, it instead outputs
50 10 50E+1
30 1.12 1.2
Upvotes: 1
Views: 421
Reputation: 204310
I don't understand the details of your question but to change a field without changing the field separators you use a regexp on the whole record. Look:
$ echo 'a;b;c;d' | awk -F';' '{$3="X"}1'
a b X d
$ echo 'a;b;c;d' | awk 'match($0,/^([^;]*;){2}/){head=substr($0,RSTART,RLENGTH); tail=substr($0,RSTART+RLENGTH); sub(/^[^;]*/,"",tail); $0 = head "X" tail } 1'
a;b;X;d
Yes, it's more code but it does a string replacement without changing FS to OFS. It can be done more concisely with GNU awk but since you wanted POSIX...
The alternative if your FS can't be negated is a loop with match()+substr().
If you edit your question to include a mcve with concise, testable sample input and expected output then you can get more help.
Upvotes: 1