0

I am trying to store some variables in shell command to run some process using thos variables:

for i in $(find . -type f -path '*folder*/*.json'); do
    echo $i
    basename=${i##*/}
    FILENAME=$(cut -d'_' -f2- "$basename") 
    PAR1="${FILENAME%%.*}_label"
    PAR2="${FILENAME%%.*}.format"
    SUFFIX= `echo $basename rev | cut -d'_' -f 1 | rev`
done

But variables FILENAME AND SUFFIX doesn't do what expected

i.e. (expected values)

i=./path/to/1_test_file.json

basename=1_test_file.json
FILENAME=test_file.json
PAR1=test_file_label
PAR2=test_file.format
SUFFIX= file.json

I have checked in similar post with similar questions here, which suggest similar approach to what I did but doesnt work...

gcj
  • 280
  • 2
  • 12
  • 1
    The space after `SUFFIX=` is a problem. `SUFFIX=${FILENAME##*_}` is probably what you want. – glenn jackman Sep 28 '22 at 14:28
  • 1
    Get out of the habit of using ALLCAPS variable names, leave those as reserved by the shell. One day you'll write `PATH=something` and then [wonder why](https://stackoverflow.com/q/27555060/7552) your [script is broken](https://stackoverflow.com/q/28310594/7552). – glenn jackman Sep 28 '22 at 14:30
  • @gardener I have modified the i.e. and add that the i.e is the expected – gcj Sep 28 '22 at 14:31
  • Why do you revert to using backticks for the last assignment? You obviously know how to use `$(...)`, you should use it consistently. – Barmar Sep 28 '22 at 14:35

1 Answers1

0
    FILENAME=$(cut -d'_' -f2- "$basename") 

The abive attempts to read the data in the file "$basename", not the string value of the variable.

Use a here-string

$ basename=1_test_file.json
$ FILENAME=$(cut -d_ -f2- <<<"$basename")
$ declare -p basename FILENAME
declare -- basename="1_test_file.json"
declare -- FILENAME="test_file.json"
glenn jackman
  • 238,783
  • 38
  • 220
  • 352