0

I would like to know how I can print the string I have but without having the last two characters in bash. for example:

str = "hello.c"

And then print only hello

Thank for answers.

1 Answers1

1

The answer is to use bash-builtin string manipulation:

str="hello.c"
echo "${str%.c}"

Try it online!

To quote the documentation:

${parameter%word}
${parameter%%word}

The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the '%' case) or the longest matching pattern (the '%%' case) deleted. If parameter is '@' or '*', the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with '@' or '*', the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

MechMK1
  • 3,278
  • 7
  • 37
  • 55
  • Quote: `echo "${str%.c}"`. Otherwise, if `IFS=l`, you'd print `he o` as output; or, with the default IFS, if the string had a literal tab you'd change it to a space (a whitespace-surrounded glob would be replaced with a list of names in the current directory, etc). – Charles Duffy Feb 02 '18 at 22:22
  • @CharlesDuffy I added that. thanks – MechMK1 Feb 02 '18 at 22:23
  • 1
    Please also consider finding a better reference than the ABS -- half the time we spend in the freenode #bash channel is helping people unlearn bad habits they picked up there. [The bash-hackers' wiki reference on parameter expansion](http://wiki.bash-hackers.org/syntax/pe) is a good source. Another is [BashFAQ #100](http://mywiki.wooledge.org/BashFAQ/100). And of course there's the [official manual](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) as well. – Charles Duffy Feb 02 '18 at 22:23
  • Thank you very much. I am a real noob in shell script. –  Feb 02 '18 at 22:33
  • @CharlesDuffy I changed it now, citing the official documentation instead of what I had before. – MechMK1 Feb 02 '18 at 22:44