How to convert CSV to TSV using perl -pe?
Question
How to convert CSV to TSV using perl -pe?
Converting CSV to TSV Using perl -pe One-Liner
When converting CSV (Comma-Separated Values) to TSV (Tab-Separated Values), the simplest approach with Perl is to replace commas with tabs. The -p flag causes Perl to read the input line-by-line, apply the provided code, and print the result automatically. The -e flag lets you supply code snippets directly on the command line.
The error in the original example was caused by attempting to run a perl -pe "..." snippet inside a Perl script or without the perl command properly invoked. The snippet perl -pe "s/,/\\t/g" is a shell command, not a Perl program by itself. For a Perl script or code block you can run with perl -, the logic must be embedded directly in Perl syntax.
Correct Runnable Perl Code to Convert CSV to TSV
Here is a minimal Perl example that reads lines from standard input, substitutes commas with tabs, and prints the output:
use strict;
use warnings;
while (<>) {
s/,/\t/g;
print;
}
How to run: Save the above in a file or run directly as perl - and enter CSV lines, then Ctrl+D (Unix) or Ctrl+Z (Windows) to finish. It will print the TSV output.
Explanation of Perl Concepts
while (<>)reads each line from ARGV or STDIN.The substitution
s/,/\t/greplaces all commas with tab characters\t.printoutputs the modified line.The
strictandwarningspragmas help catch errors and enforce good coding practices.This demonstrates Perl’s famous TMTOWTDI philosophy—many ways to achieve the same task, here through command line one-liners or scripts.
Common Pitfalls
Replacing commas blindly does not handle quoted CSV fields properly (e.g.,
"Smith, John"will be broken).When using the
perl -pe "s/,/\\t/g"one-liner in a shell, use double quotes to interpret\tcorrectly.Trying to run the
perl -pe ...snippet directly inside a Perl script leads to syntax errors because it’s a shell command, not pure Perl code.For robust CSV parsing, consider the
Text::CSVmodule, but it requires a full script, not just-pe.
Summary
To convert CSV to TSV on the command line quickly with Perl, use the shell one-liner:
perl -pe "s/,/\t/g"
Or, for a self-contained Perl script runnable with perl -, use:
use strict;
use warnings;
while (<>) {
s/,/\t/g;
print;
}
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 13ms
(empty)(empty)