# Tidy CSV: Trim, Dedupe and Sort (`brightwater-tools/csv-cleaner-deduplicator`) Actor

CSV clean-up: trim cells, snake_case headers, drop empty rows, remove duplicates on all columns or chosen key columns, and optionally sort. Output CSV or JSON with a summary. The cleaning code makes no network calls and does no scraping.

- **URL**: https://apify.com/brightwater-tools/csv-cleaner-deduplicator.md
- **Developed by:** [Brightwater Tools](https://apify.com/brightwater-tools) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 successful csv clean-ups

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Tidy CSV: Trim, Dedupe and Sort

Clean a CSV in one run: trim stray spaces, tidy the column names, drop empty rows, remove duplicate rows, and optionally sort. Paste your CSV, choose the options, and get a clean table back as CSV or JSON, with a short summary of what changed.

The cleaning code makes no network calls and reads nothing except the CSV you paste in. It does not fetch URLs or scrape websites.

**$0.005 per successful clean-up** (UNCONFIRMED against the live Store). Failed runs are not charged.

### What you can do with it

- Tidy a **supplier price list** or a **parts list** exported from a spreadsheet before you import it somewhere else.
- Remove **duplicate rows**, either when the whole row matches or when only key columns such as `part_name,supplier` match.
- Convert a **European semicolon CSV** (or a tab-separated file) into clean CSV or JSON for an API.
- **Sort** a table by one column, with numbers sorted as numbers.
- Turn messy headers such as `Unit Cost (USD)` into simple names such as `unit_cost_usd`.

### How to use it

1. Paste the whole CSV into **CSV text**. The first row must hold the column names.
2. Set the options you need. The defaults trim spaces, rename headers, drop empty rows and remove exact duplicate rows.
3. Click **Start**. The cleaned table appears in the **Output** tab and the dataset.

#### Example: cleaned CSV

Example input:

```json
{
  "csv_text": "Part Name,Unit Cost (USD),Qty\n  Bolt M6 ,1.25, 10\nBolt M6,1.25,10\n,,\nNut M6,0.40,25\n",
  "output_format": "csv"
}
```

Output (one dataset item):

```json
{
  "output_format": "csv",
  "rows_in": 4,
  "rows_out": 2,
  "empty_rows_removed": 1,
  "duplicates_removed": 1,
  "columns": ["part_name", "unit_cost_usd", "qty"],
  "content": "part_name,unit_cost_usd,qty\nBolt M6,1.25,10\nNut M6,0.40,25\n"
}
```

What happened: the spaces around `Bolt M6` and `10` were trimmed, the headers were renamed, the all-blank row was dropped, and the second `Bolt M6` row was removed as a duplicate of the first.

#### Example: JSON

Set `output_format` to `json` with the same `csv_text`. The `content` field then holds a JSON array with one object per row, keyed by the cleaned column names:

```json
[
  {
    "part_name": "Bolt M6",
    "unit_cost_usd": "1.25",
    "qty": "10"
  },
  {
    "part_name": "Nut M6",
    "unit_cost_usd": "0.40",
    "qty": "25"
  }
]
```

Values stay as text, so `1.25` appears as `"1.25"`.

#### Summary fields

Every successful run returns these fields. A failed run returns no summary, only an error message.

| Field | Meaning |
|---|---|
| `output_format` | `csv` or `json`, the format of `content` |
| `rows_in` | Data rows read, not counting the header |
| `rows_out` | Data rows in the cleaned table |
| `empty_rows_removed` | Rows removed because every cell was blank |
| `duplicates_removed` | Rows removed as duplicates of an earlier row |
| `columns` | The cleaned column names, in order |
| `content` | The cleaned table: CSV text, or a JSON array when `output_format` is `json` |

### Input fields

| Field | Default | What to enter |
|---|---|---|
| `csv_text` | a short sample | The whole CSV. Required. The first row is the header. |
| `delimiter` | `,` | One character that separates fields. Use `;` or a tab for European or tab-separated files. |
| `output_format` | `csv` | `csv` or `json`. |
| `trim_cells` | on | Remove spaces around every cell. Turn off to keep the spaces in cells. Headers are always trimmed. |
| `snake_case_headers` | on | Rename headers to lower case with underscores. A blank header becomes `column_N`, where N is its position. |
| `drop_empty_rows` | on | Remove rows where every cell is blank. The number removed is in the summary. |
| `dedupe` | `all_columns` | `off` keeps every row. `all_columns` removes a row when every cell matches an earlier row. `key_columns` removes a row when the key columns match an earlier row. The first row of each group is kept. |
| `key_columns` | empty | Comma-separated column names, for example `part_name,supplier`. Needed when `dedupe` is `key_columns`. |
| `sort_by` | empty | One column name to sort by, after duplicates are removed. Leave empty to keep the original order. |
| `sort_order` | `asc` | `asc` (smallest first) or `desc` (largest first). Used only when `sort_by` is set. |
| `max_input_bytes` | 1,000,000 | The largest CSV accepted, in bytes. The hard limit is 5,000,000. |

### Pricing

- **$0.005 per successful run** (UNCONFIRMED against the live Store) (event `conversion`). One run cleans one CSV, whatever its size up to the limit.
- **Failed runs** (bad input, a wrong option, a CSV that cannot be read) are **not charged**.
- **Small files:** the price is the same flat amount for any file size. For files of about six rows or fewer, some per-row actors in this category cost the same or less, at the prices their Store pages showed on 2026-10-26. Compare before you choose.

### Limits

- **Size limit:** the CSV can be up to 1 MB by default (`max_input_bytes`, up to 5 MB). The limit counts bytes, so accented text takes more than one byte per character.
- **Values stay as text.** Numbers are not reformatted: `1.20` stays `1.20`, and JSON output holds every value as a string.
- **No formula escaping.** Cells that start with `=`, `+`, `-` or `@` are written as they are. The actor adds no quote or other escape, so Excel and Google Sheets may treat them as formulas. Check untrusted data before you open the output in a spreadsheet.
- **Sorting uses Unicode code points.** Numbers such as `1.25`, `-3` or `1e3` sort by value. Other text sorts by code point, so capital letters come before lower-case ones (`B` before `a`). This is not a locale-aware sort, so accented letters do not sort next to their base letter.
- **Duplicates are exact matches** after trimming (when trimming is on), and they are case-sensitive: `bolt` and `Bolt` are different.
- **Blank means blank even with trimming off.** A cell that holds only spaces counts as blank when empty rows are dropped and when `sort_by` places blank cells last. With `trim_cells` off, such a cell is still written with its spaces, and duplicate removal still compares it exactly.
- **Column names must be unique after cleaning.** If two headers become the same name, for example `Unit Cost` and `unit_cost`, the run stops and asks you to rename one.
- **Ragged rows:** a row with fewer values than the header is padded with blanks. A row with more values than the header stops the run, and the message gives its line number.
- **Sorting rules:** blank cells always go last, in both directions. In `desc` order, text comes before numbers, because the whole order is reversed. Only one sort column is allowed.
- **One delimiter character:** the delimiter must be a single character that is not a quote or a line break.
- **Values are never reformatted:** dates, currency symbols and decimal places are kept as typed. The one change is that spaces around a value are removed when `trim_cells` is on, which is the default.

### FAQ

**Does it send my data anywhere?** No. The cleaning makes no outside requests. It runs inside your Apify run, and the result is saved to your run's dataset on Apify, as with any Apify actor.

**Will it change my numbers or dates?** No. Values are kept as text and never reformatted. Trimming cell spaces, renaming headers, dropping empty rows and removing duplicates are on by default, and each can be turned off. Header spaces are always trimmed, whatever `trim_cells` is set to. Sorting is off until you set `sort_by`.

**Can I call it from code?** Yes, through the Apify API or the Apify client for JavaScript or Python, like any Apify actor.

**I found a bug or need a feature.** Open an issue on this actor's Issues tab.

### AI use

This actor was written with the help of AI coding tools. The rules above describe exactly what the cleaning does.

***

Made by Brightwater Tools.

# Actor input Schema

## `csv_text` (type: `string`):

The whole CSV document to clean. The first row must be the header. Nothing is fetched from a URL or read from a file. The size limit is max_input_bytes.

## `delimiter` (type: `string`):

One character that separates fields in the input, and is also used for CSV output. Use ',' for comma, ';' for semicolon or a tab character for tab-separated files.

## `output_format` (type: `string`):

'csv' writes the cleaned table as CSV. 'json' writes a JSON array with one object per row, keyed by the cleaned column names. Values stay as text in both formats.

## `trim_cells` (type: `boolean`):

Remove leading and trailing whitespace from every header and cell before the other steps run. Turn off to keep the spaces.

## `snake_case_headers` (type: `boolean`):

Rename headers to lower_case_with_underscores, for example 'Unit Cost (USD)' becomes 'unit_cost_usd'. A blank header becomes column_N, where N is its position. Two headers that end up with the same name are refused.

## `drop_empty_rows` (type: `boolean`):

Remove rows in which every cell is blank. The number removed is reported in the summary.

## `dedupe` (type: `string`):

'off' keeps every row. 'all_columns' removes a row when every cell matches an earlier row. 'key_columns' removes a row when the cells in key_columns match an earlier row. The first row of each group is kept.

## `key_columns` (type: `string`):

Comma-separated column names used when 'Remove duplicate rows' is key_columns, for example 'part_name,supplier'. Names are matched after the snake_case step, or as written when that step is off. Ignored otherwise.

## `sort_by` (type: `string`):

One column name to sort the rows by, after duplicates are removed. Numbers sort by value, text sorts by character code, and blank cells always go last. Leave empty to keep the original order.

## `sort_order` (type: `string`):

'asc' sorts from smallest to largest, 'desc' from largest to smallest. Used only when 'Sort by column' is set.

## `max_input_bytes` (type: `integer`):

Input larger than this is refused with an error. The hard ceiling is 5,000,000 bytes.

## Actor input object example

```json
{
  "csv_text": "Part Name,Unit Cost (USD),Qty\n  Bolt M6 ,1.25, 10\nBolt M6,1.25,10\n,,\nNut M6,0.40,25\n",
  "delimiter": ",",
  "output_format": "csv",
  "trim_cells": true,
  "snake_case_headers": true,
  "drop_empty_rows": true,
  "dedupe": "all_columns",
  "key_columns": "",
  "sort_by": "",
  "sort_order": "asc",
  "max_input_bytes": 1000000
}
```

# Actor output Schema

## `results` (type: `string`):

One item per run: the cleaned table as CSV or JSON in 'content', plus the summary counts (rows in and out, empty rows and duplicates removed, column names).

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("brightwater-tools/csv-cleaner-deduplicator").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("brightwater-tools/csv-cleaner-deduplicator").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call brightwater-tools/csv-cleaner-deduplicator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,brightwater-tools/csv-cleaner-deduplicator"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/YM9zM3l1ramZGUDBD/builds/rDeOa1UnUi8wCvaNW/openapi.json
