'Shell script name parsing [duplicate]

I have a variable FILE_NM in shell script which has "abc_xyz_mno_123" value in it. I want to get only "abc_xyz_mno" out of it in another variable. How to do it?

I tried :

NEW_NAME = $( echo $FILE_NM | rev | cut -d'_' -f2 | rev)

It gives me out put "xyz" only but i need entire name except last delimited value by '_'

Any suggestions?



Solution 1:[1]

A parameter expansion is the tool for this job:

NEW_NAME=${FILE_NM%_*}

The ${var%suffix} expansion strips the shortest match of the pattern suffix from the end of $var during expansion


By the way -- all-caps names are used for built-in variables, particularly including environment variables with POSIX-defined meaning that reflect or modify behavior of the shell or standard utilities. As described by the standards document at https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html, you should use lowercase names for variables you define yourself so you can't modify a variable that controls shell behavior by mistake.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1