sj755
sj755

Reputation: 4062

Specify a "-" in a sed pattern

I'm trying to find a '-' character in a line, but this character is used for specifying a range. Can I get an example of a sed pattern that will contain the '-' character?

Also, it would be quicker if I could use a pattern that includes all characters except a space and a tab.

Upvotes: 0

Views: 103

Answers (3)

Keith Thompson
Keith Thompson

Reputation: 263237

'-' specifies a range only between square brackets.

For example, this:

sed -n '/-/p'

prints all lines containing a '-' character. If you want a '-' to represent itself between square brackets, put it immediately after the [ or before the ]. This:

sed -n '/[-x]/p'

prints all lines containing either a '-' or a 'x'.

This pattern: [^ <tab>]

matches all characters other than a space and a tab (note that you need a literal tab character, not "<tab>").

Upvotes: 6

ghostdog74
ghostdog74

Reputation: 342353

find "-" in file

 awk '/-/' file

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753675

If you want to find a dash, specify it outside a character class:

/-/

If you want to include it in a character class, make it the first or last character:

/[-a-z]/
/[a-z-]/

If you want to find anything except a blank or tab (or newline), then:

/[^ \t]/

where, I hasten to add, the '\t' is a literal tab character and not backslash-t.

Upvotes: 2

Related Questions