How to print 7 chars from left of filemane?

Hi Guys

Kindly help me on my predicament. I want to get the 7 chars of this filename

I need to get the ALL.cmd from this filehame filename_a_ALL.cmd

Thanks

That file name is in a

  • shell variable
  • program variable
  • (text) file
    ?

the value will be coming from for loop

In a shell variable?

yes it is..

thanks a lot :slight_smile:

Try this if you want to use the underscore as separator:

foo=filename_a_ALL.cmd
echo "${foo##*_}"

Or, if it really needs to be the last 7 characters:

echo "${foo#"${foo%???????}"}"

What shell are you using (and what version of that shell)?

What operating system are you using?

Wouldn't "7 chars from left of filemane(sic)" when the filename is filename_a_ALL.cmd be filenam instead of ALL.cmd ?

sorry it should be from right to left. I stand corrected.

Thanks to you sir.

Assuming that you're using a shell that performs basic POSIX-required parameter expansions, Scrutinizer already gave you two ways to do what you want in post #6 in this thread.

If you aren't using a POSIX-conforming shell, you need to answer the questions I raised in post #7 in this thread so we can help you find something that will work in your environment.

1 Like

Hi Scrutinizer,

Thanks this works for me.

echo "${foo#"${foo%???????}"}"

You are welcome, in bash, ksh93 and zsh you can also do this:

echo "${foo: -7}"