Reputation: 23492
I want to insert a comma after the first column and as well as before the last column of all the lines of a file in which each line has a varying number of fields.
E.g. this is file:
test1 test2 test3
test1 test2 test3 test4 test5 test6
test1 test2 test3 test4
test1 test2 test3 test4 test5
I want to make it look like:
test1, test2, test3
test1, test2 test3 test4 test5, test6
test1, test2 test3, test4
test1, test2 test3 test4, test5
I ma trying something like following but it is not working (either syntax error OR no expected output):
awk '{NF=NF-1;for (i=NF; i==NF; i--) $i="," print $NF }' my_file1
Upvotes: 1
Views: 8764
Reputation: 246754
If you're interested in a sed answer: sed -e 's/ /, /' -e 's/\(.*\) /\1, /'
Upvotes: 2
Reputation: 96258
awk '{ $1=$1","; $(NF-1)=$(NF-1)","; print }'
note: if NF=2 this will insert two commas after the first field, which is in line with what you asked but probably not what you really want. if you want to handle it just add an extra if
.
Upvotes: 3
Reputation: 141780
You don't need that for
-loop. You're just changing two fields.
I find newlines (and other whitespace) can make awk
(and other languages) a whole lot more readable:
% awk '{
$1 = $1","
$(NF - 1) = $(NF - 1)","
print
}
' my_file1
test1, test2, test3
test1, test2 test3 test4 test5, test6
test1, test2 test3, test4
test1, test2 test3 test4, test5
Upvotes: 3