Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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:


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
Why not awk? awk -F, -v OFS=, '{tmp=$2;$2=$3;$3=tmp;print}' – Kevin Apr 2 '12 at 2:37


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
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

Non-sed solution using q:

$ q -d, -H -O  'select [student-id],first,last,hwk1,hwk2,hwk3,exam1,hwk4,hwk5,exam2 from sample.csv' 
share|improve this answer

Your Answer


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.