When I run grep like this, I can see the matches as expected:

$> echo -ne 'foo\nfoo\n' > file_a
$> grep -Hn foo file_a

But when I create a file with carriage returns in it, grep gives me unexpected output:

$> echo -ne '\x0dfoo\x0dfoo\nfoo\n' > file_b
$> grep -Hn foo file_b

Can anyone explain why it gives this output?


It's not unexpected. The carriage return moves the cursor to the start of the line. grep has already printed out the file's name and the line number, and the contents of the matching line overwrites this (due to the carriage return before and after the first foo on the line).

Carriage returns may also be written as \r:

printf '\rfoo\rfoo\nfoo\n' >file

This will create a file with two lines. The first line will contain the word foo twice, but the carriage returns will move the cursor to the start of the line. If using catto view this file, it will look as if there's only one foo on the first line.

Not the answer you're looking for? Browse other questions tagged or ask your own question.