0

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?

Charles Duffy
  • 257,635
  • 38
  • 339
  • 400
  • `NEW_NAME="$(printf %s "$FILE_NM" | cut -d_ -f1-3)"`? – Biffen Feb 04 '22 at 13:53
  • The command given in the question will emit `NEW_NAME: command not found`, because of the spaces around the `=`. Also, it's prone to the bugs described in [I just assigned a value, but `echo $value` shows something else!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Feb 04 '22 at 13:54
  • 1
    Hi, and welcome to Stack.Overflow. Just to confirm, when you say that it “has "abc_xyz_mno_123" value in it”, does the value of that variable contain the quote (“) characters ? (It’s just that you seem to have that quote character in your `cut` command : `cut -d''` ) – racraman Feb 04 '22 at 13:55
  • `NEW_NAME="$(printf %s "$FILE_NM" | awk -F_ -v OFS=_ '{ NF--; print }')"`? – Biffen Feb 04 '22 at 13:56

1 Answers1

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.

Charles Duffy
  • 257,635
  • 38
  • 339
  • 400