I was wondering if there was a simple way to add exceptions to the [[:punct:]] bracket expression when using tr utility:

cat *.txt | tr '[[:punct:]]' '\012'

for instance: do not do anything if the punctuation characters are - or ).

share|improve this question
up vote 2 down vote accepted

You can use a negative look-ahead: '(?![-)])[[:punct:]]'

This will first check whether the next character is neither a -nor a ), and then check it for whether it's a punctuation character. Using a negative look-behind is also possible and might or might not be faster: '[[:punct:]](?<![-)])'

edit: since tr apparently doesn't support Regex (only basic POSIX), you should use another utility, e.g. sed: cat *.txt | sed -r 's/(?![\-@\/\\¤%+[&|=^\]$_*#])[[:punct:]]/\012/g'

share|improve this answer
    
Thanks Njol, that's perfect – bobylapointe Jan 22 '14 at 21:45
    
@bobylapointe then please accept the answer ;) – Njol Jan 22 '14 at 21:47
    
done. Just a little things: it says "range-endpoints of '[-)' are in reverse collating sequence order". Any idea why this happens? – bobylapointe Jan 22 '14 at 21:51
    
Negative lookahead in tr? – anubhava Jan 22 '14 at 21:56
1  
@bobylapointe I just checked the documentation and it appears that tr is a very old command that uses a very early POSIX syntax, i.e. it's impossible to use any advanced Regex features (like look-aheads), unlike e.g. Perl's tr, sorry. You could use the more advanded sed instead: cat *.txt | sed 's/(?![\-@/\¤%+[&|=^]$_*#])[:punct:]/\012/g' (didn't test this, you might have to use the -E flag, and/or change the \012 to non-octal form) – Njol Jan 22 '14 at 22:23

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.