extract part of string using sed
65,883
Solution 1
[oracle.*]
means "one of the characters o, r, a, c, l, e, ., or *". Consequently, your regex will only match something like
lib+c.txt
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-11.2.0.3.0.txt | sed 's/lib.\(oracle.*\)\.txt/\1/'
However, a much simpler way of doing that is
basename lib/oracle-11.2.0.3.0.txt .txt
or, if you really want the file to come from stdin
:
ls lib/oracle-11.2.0.3.0.txt | xargs -I{} basename {} .txt
Solution 2
Here are a few more ways of doing this:
Perl
echo "lib/oracle-11.2.0.3.0.txt" | perl -pe 's/.+(oracle.+)\.txt/$1/'
sed
echo "lib/oracle-11.2.0.3.0.txt" | sed 's/.*\(oracle.*\)\.txt/\1/'
cut
echo "lib/oracle-11.2.0.3.0.txt" | cut -d'/' -f 2 | cut -d '.' -f 1-5
basename
andbash
echo "lib/oracle-11.2.0.3.0.txt" | while read n; do echo $(basename ${n/.txt//}); done
Solution 3
How about using cut
echo "lib/oracle-11.2.0.3.0.txt" | cut -c5-19
Related videos on Youtube
Comments
-
would_like_to_be_anon over 1 year
ls lib/oracle-11.2.0.3.0.txt | 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-11.2.0.3.0.txt" | awk -F/ '{print substr($2,1,index($0,".txt")-1);}'