0

I want to extract filename by removing prefix and extension. e.g. file=foo_filename.txt

I am using this,but its not working.

${file#foo_%.txt}

Thanks

Rgeek
  • 419
  • 1
  • 9
  • 23
  • Be sure to check out [Parameter Expansion](http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion) on Greg's Wiki. – w0ng Jan 15 '14 at 21:39

2 Answers2

2
file="foo_filename.txt"
file=${file#foo_}
file=${file%.*}
echo "$file"
that other guy
  • 116,971
  • 11
  • 170
  • 194
1

You got it almost right:

file=foo_filename.txt ;  echo ${file%.txt}

Or for example in one step with sed:

file=foo_filename.txt ;  echo ${file} | sed 's/^foo_\(.*\)\..*/\1/'

Yet another method:

file=foo_filename.txt ; basename -s .txt ${file#foo_}

You cannot "nest" variable expansion in bash: Can ${var} parameter expansion expressions be nested in bash?

Community
  • 1
  • 1
Jakub Kotowski
  • 7,411
  • 29
  • 38