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.
ls lib/oracle- | sed 's/lib.\([oracle.*]\)\.txt/\1/'

It is giving the whole string instead of just oracle part until .txt What am I doing wrong?

I can do it using awk as follows, but, not sure why sed is not giving the wanted result.

echo "lib/oracle-" | awk -F/ '{print substr($2,1,index($0,".txt")-1);}'
share|improve this question

3 Answers 3

up vote 12 down vote accepted

[oracle.*] means "one of the characters o, r, a, c, l, e, ., or *". Consequently, your regex will only match something like


and not the actual filename you're passing it. If you remove the [ and ] from the regex, then it will work fine:

ls lib/oracle- | sed 's/lib.\(oracle.*\)\.txt/\1/'

However, a much simpler way of doing that is

basename lib/oracle- .txt

or, if you really want the file to come from stdin:

ls lib/oracle- | xargs -I{} basename {} .txt
share|improve this answer

Here are a few more ways of doing this:

  1. Perl

    echo "lib/oracle-" | perl -pe 's/.+(oracle.+)\.txt/$1/'
  2. sed

    echo "lib/oracle-" | sed 's/.*\(oracle.*\)\.txt/\1/'
  3. cut

    echo "lib/oracle-" | cut -d'/' -f 2 | cut -d '.' -f 1-5
  4. basename and bash

    echo "lib/oracle-" | while read n; do 
      echo $(basename ${n/.txt//}); 
share|improve this answer
I think the OP is trying to get the filename without .txt extension. –  don_crissti Jun 26 '13 at 20:35
@don_crissti I think you are absolutely right. Thanks, answer modified. –  terdon Jun 26 '13 at 21:04

How about using cut

echo "lib/oracle-" | cut -c5-19
share|improve this answer

Your Answer


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.