The following commands assume that the cells in the CSV files do not contain newlines and commas. Otherwise, you should write a more complicated script in Perl, PHP, or other programming language capable of parsing CSV files properly. But Bash, definitely, is not appropriate for this task.
Perl
perl -F, -nle '@F = reverse @F if $F[0] =~ /^"\d+"$/;
print join(",", @F)' file
Beware, If the cells contain newlines, or commas, use Perl's Text::CSV
module, for instance. Although it is a simple task in Perl, it goes beyond the scope of the current question.
The command splits the input lines by commas (-F,
) and stores the result into @F
array, for each line. The items in the array are reversed, if the first field $F[0]
matches the regular expression. You can also swap the items this way: ($F[0], $F[1]) = ($F[1], $F[0])
.
Finally, the joins the array items with commas, and prints to the standard output.
If you want to edit the file in-place, use -i
option: perl -i.backup -F, ...
.
AWK
awk -F, -vOFS=, '/^"[0-9]+",/ {print; next}
{ t = $1; $1 = $2; $2 = t; print }' file
The input and output field separators are set to ,
with -F,
and -vOFS=,
.
If the line matches the pattern /^"[0-9]+",/
(the line begins with a "numeric" CSV column), the script prints the record and advances to the next
record. Otherwise the next block is executed.
In the next block, it swaps the first two columns and prints the result to the standard output.
If you want to edit the file in-place, see answers to this question.