Skip to content
shellhacks.dev
Text Processing

Find Files with Windows (CRLF) Line Endings Using grep

Find files with Windows line endings using grep -l and a carriage return from Bash ANSI-C quoting, then strip them with sed. A dollar sign counts only line ends.

1 min read
Summarize in AI

A script fails on a file that came from Windows, and you suspect carriage returns at the end of its lines.

Shell
printf 'unix\n' > u.txt
printf 'dos\r\nline2\r\n' > d.txt
grep -l $'\r' *.txt
grep -c $'\r$' d.txt
sed -i 's/\r$//' d.txt
grep -c $'\r' d.txt
Text
d.txt
2
0

A Windows line ends with a carriage return and a line feed, and grep strips only the line feed, so the carriage return stays part of the line. Bash expands the ANSI-C string for a carriage return into the real character, -l lists the files that contain one, and adding a dollar sign limits the match to the end of a line, which counted two lines in d.txt. A sed -i substitution then removed them, and the count dropped to 0. See ANSI-C Quoting and grep options.

sed -i rewrites the file in place, so keep a copy or use -i.bak, and on macOS the BSD sed needs -i ''. Check binary files and files with mixed line endings before converting them. dos2unix does the same job where it is installed.

Taggedgreptext
Share

More snippets

Text Processing

Replace Only the Nth Match on a Line with sed

Replace only the second or a later match on a line with a numeric flag on the s command, and add g to replace from that match onward. The count restarts on every line.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.