Pankaj K
Pankaj K

Reputation: 351

How to grep "\n" in file

Sample file : abc.ksh

echo "This is a sample file." >> mno.txt
echo "\nThis line has new line char." >> mno.txt

I want

echo "\nThis line has new line char." >> mno.txt

as output.

Upvotes: 16

Views: 60984

Answers (6)

Rahul Tripathi
Rahul Tripathi

Reputation: 172568

You may try like this by escaping the backslash with another backslash:

grep '\\n' xyz.ksh

Upvotes: 0

Velizar VESSELINOV
Velizar VESSELINOV

Reputation: 2374

Regular expression pattern search

grep -P '\n' mno.txt

Upvotes: 2

CliffordVienna
CliffordVienna

Reputation: 8255

Simply escape the backslash with another backslash and put the regex in single quotes so the shell does pass it to grep without handling the backslashes itself:

grep '\\n' abc.ksh

Upvotes: 3

Feleppo Bubba
Feleppo Bubba

Reputation: 59

Easiest way is using REGEX:

grep "$" filename  # this will match all lines ending with "\n" (often all lines)
grep "PATTERN$"    # this will match all lines ending with "PATTERN\n"

In REGEX language, $ means EOL (end of line), so it will often match "\n" (cause is very common as the end of line).

WARNING: be careful to use versions of grep that support REGEX!.

Upvotes: 5

fedorqui
fedorqui

Reputation: 290125

Use -F to match fixed strings:

$ grep -F "\n" file
echo "\nThis line has new line char." >> mno.txt

From man grep:

-F, --fixed-strings

Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified by POSIX.)

Upvotes: 20

Crusader
Crusader

Reputation: 1200

grep -zoP '[^\n]*\n[^\n]*' file

  • -z - change all \n to zero byte
  • -o - show only diff (because whole file is one line for grep now)
  • -P - perl regexp

find \n and line before and after

Upvotes: 2

Related Questions