slayedbylucifer
slayedbylucifer

Reputation: 23492

Insert a comma after first column and before last column

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

Answers (3)

glenn jackman
glenn jackman

Reputation: 246754

If you're interested in a sed answer: sed -e 's/ /, /' -e 's/\(.*\) /\1, /'

Upvotes: 2

Karoly Horvath
Karoly Horvath

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

johnsyweb
johnsyweb

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

Related Questions