one-liners beginner

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/g replaces all commas with tab characters \t.

  • print outputs the modified line.

  • The strict and warnings pragmas 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 \t correctly.

  • 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::CSV module, 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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions