8

I have a file with values organized in columns, and separated by commas, as in the file below:

324,01,1,113333600000,1,,
016,01,1,134954200000,1,,
770,01,1,109069200000,1,,
853,01,1,111518800000,1,,

When I use the following awk command, the delimiter is being changed from commas to spaces

Code:

awk -F, '{$4=$4/1024}{print $0}'

The output becomes:

324 01 1 110677343.75 1  
016 01 1 131791210.93 1  
770 01 1 106512890.62 1  
853 01 1 108905078.12 1 

How can I change the value of the field without changing the delimiter?

3 Answers 3

18

Set OFS as well:

awk -F, -v OFS=, '{$4=$4/1024}1'

The OFS determines how output fields are delimited. If you don't set it, the default is a space.

7

muru answer is correct, but I prefer using the BEGIN block for this task:

awk 'BEGIN{FS=OFS=","}{$4=$4/1024}1'
-1

There is a problem with the given answers in gawk:

If no field was changed on the record, setting OFS may get ignored.

Putting the following line inside your record processing will solve this:

$1=$1;

A complete example to change the separator to ";" would be:

</etc/passwd awk -F: -v OFS=; '{$1=$1; print}'
3
  • 1
    If no fields were changed, this would not be an issue, but the code in the question does change the value of fields. The question is not about how to change the delimiter but how to retain it. Commented Apr 6 at 8:12
  • FS=OFS="," is about keeping the original separator by setting both separators the same value. However, when FS is implicit, awk sets OFS to " ", even if the field separator was virtually "\t". Commented Apr 6 at 21:10
  • 1
    My comment is about the fact that the question contains awk code that modifies a field, and you start out saying that OFS may be ignored if nothing is changed. If you want to comment on other answers, then do that in a comment. You can also edit or suggest edits to existing answers. When you answer , you will need to address the question, not other answers. Commented Apr 7 at 5:51

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.