Explain Codes LogoExplain Codes Logo

'^m' character at end of lines

career
interview-preparation
best-practices
soft-skills
Alex KataevbyAlex Kataev·Sep 3, 2024
TLDR

Banish the ^M (carriage return - CR) from SQL strings with REPLACE:

UPDATE my_table SET my_column = REPLACE(my_column, CHAR(13), '');

CHAR(13) pinpoints the ^M fiend; firing off a REPLACE on my_column sends it packing.

Investigating the '^M' mystery

Those sneaky ^M characters you're spotting at line ends are carriage returns hailing from the DOS/Windows neck of the woods, where line boundaries are outlined by a carriage return (CR) trailed by a line feed (LF), depicted as \r\n. In contrast, Unix systems prefer the minimalist approach and use a solitary line feed (LF), represented as \n, for line cutoffs. When a DOS/Windows borough file (CR + LF) embarks on a Unix excursion, the CR pulls a 007 and masquerades as ^M.

Juggling different environments

Tweaking file formats in vi or vim like a pro:

:set fileformat=unix " Hey ^M, it's not me – it's Unix. Let's break up! :w " Save the break-up note

Deploying dos2unix like you're launching code missiles:

dos2unix filename " dos2unix in action - Swapping hats from DOS to Unix. Bye-bye ^M!

Remember to peruse the man-pages for dos2unix. Knowledge is power!

Origin OS playing hide and seek:

When the birthplace OS of your script or text file eludes you, utilities like file or hexdump will play the detective and reveal those line-separating brutes.

The awkward tango between SQL and '^M'

Amidst the beautiful ballet of SQL database operations, the insidious ^M character may occasionally gatecrash the party, bulldozing its way through script imports, user inputs, or unguarded data sources.

Restoring order in your SQL kingdom:

-- Clean new entries: "^M, you're not on the guest list!" INSERT INTO my_table (my_column) VALUES (REPLACE(input_data, CHAR(13), '')); -- Scrub existing data: "^M, your misadventures end here!" UPDATE my_table SET my_column = REPLACE(my_column, CHAR(13), '');

Building a '^M'-proof fortress

Getting Git to play ball:

Tweak the core.autocrlf switch in Git to form a sturdy barrier against ^M infiltrations into your code repository.

Manipulating IDE/editor settings:

Pull the strings of your IDE or text editor to adopt Unix-style line finales when conjuring or storing files – a lifesaver in a cross-platform cosmos.

Automation to the rescue:

Draft line-ending audits into your CI/CD pipeline team or employ pre-commit hooks as vigilant gatekeepers to keep ^M outside your code turf.