Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a CSV file that contains 10 different fields (, is the deliminator). Example data:

student-id,last,first,hwk1,hwk2,hwk3,exam1,hwk4,hwk5,exam2
pts-avail,,,100,150,100,200,150,100,300
991-78-7872,Thompson,Ken,95,143,79,185,135,95,259

I need to swap field2 and field3 using sed but having a difficult time understanding how to write the regular expression.

I have tried along with other variations:

sed 's/\(.*[,]\)\(.*[,]\)\(.*[,]\)/\1\3\2/g' test

In my test file:

abc,def,ghi,jkl
1234,5678,abcd,efgh

It works fine… I have been looking at this for a while and can't figure it out. Anyone able to provide some direction?

share|improve this question
2  
Why not awk? awk -F, -v OFS=, '{tmp=$2;$2=$3;$3=tmp;print}' –  Kevin Apr 2 '12 at 2:37
add comment

1 Answer 1

Try:

sed 's/^\([^,]*,\)\([^,]*,\)\([^,]*\)/\1\3\2/'

Broken down:

'^'     start at the beginning of the line
\(  \)  a grouping
[^,]    any character except ','
*       zero or more times
,       the character ','

The \([^,]*,\) is repeated three times. The rest of the line is unchanged and unmatched.

With awk:

awk 'BEGIN {FS=OFS=","}{t=$2;$2=$3;$3=t;print}'
share|improve this answer
    
+1 for awk. Lot cleaner solution than sed –  Patrick Apr 2 '12 at 3:07
3  
Please bear in mind that these won't work if the CSV file contains fields with commas. The easiest way to cover that is to use a parser that's fully aware of CSV. –  Alexios Apr 2 '12 at 4:46
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.