Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want a regex pattern which can print all lines not containing punctuation :

Input :

.I am line 1
I am ! line 2
I am line (3)
I am line 4

Output: ( should be)

I am line 4

What I've tried so far :

grep '[^[:punct:]]' file.txt

But it shows all characters which is not punctuation.

share|improve this question
add comment

3 Answers 3

up vote 7 down vote accepted

Your grep prints all lines containing non-punctuation characters. That's not the same as printing all lines that do not contain punctuation characters.

For the latter, you want the -v switch (print lines that don't match the pattern):

grep -v '[[:punct:]]' file.txt

If, for some reason you don't want to use the -v switch, you must make sure that the whole line consists of non-punctuation characters:

grep '^[^[:punct:]]\+$' file.txt
share|improve this answer
    
+1 thanks. Is there any way without using -v switch ? –  Hamed Kamrava Jul 3 at 13:50
    
@HamedKamrava Yes. Please see my edit. –  Joseph R. Jul 3 at 13:51
    
@HamedKamrava Out of curiosity: why would you want to avoid -v? –  Bernhard Jul 3 at 13:54
    
I don't avoid -v just want to know more :) –  Hamed Kamrava Jul 3 at 13:58
    
@HamedKamrava Please don't forget to mark this answer 'Accepted' if it solved your problem. –  Joseph R. Jul 3 at 13:59
add comment

In sed you can do something like:

sed '/[[:punct:]]/!d'

In awk you can do:

awk '!/[[:punct:]]/'

share|improve this answer
add comment

A Perl ones:

perl -nle 'print unless /\p{XPosixPunct}/' file

This will match -!"#$%&'()*+,./:;<=>?@[\]^_`{|}~ which unicode consider Punctutation and Symbols.

or:

perl -nle 'print unless /\p{Punct}/' file

\p{Punct} only matches -!"#%&'()*,./:;?@[\]_{}, missing $+<=>^`|~ which unicode consider Symbols.

perl by default use POSIX locale. If you don't use perl, you should all so set LC_ALL=POSIX, because different locale can have different punctuation characters like SAA C has ¢.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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