0

Sorry, this seems to be a pretty straightforward question but I cannot find the good syntax anywhere I've been looking for...

I am in a directory with some files : a.fa and b.fa

Here is my script:

files=*
for f in $files
do

newname=$(echo $f|awk -F"/" '{print $NF;}'|cut -d'.' -f1);
less $f > less_$newname.txt
filename_$newname="less_$newname.txt"

done

With the following error:

filename_a=less_a.txt: command not found
filename_b=less_b.txt: command not found

What I would like in the end is 4 files in my directory:

a.fa
b.fa
less_a.txt
less_b.txt

And two new variables named filename_a and filename_b

Any idea on how I could do? Thanks!

9
  • 4
    xyproblem.info - Why on earth do you want variable variable names? We prefer not to hand questioners guns so they can shoot themselves on the foot. So, please explain why do you think you need this? Commented Nov 18, 2015 at 17:15
  • I have a script with many variables of two 'kinds' A and B generated by a for loop. I would thus like in the end to have variables Aa, Ab, Ac VS Ba, Bb, Bc and it seemed to me that it would be easy to name them this way :) Commented Nov 18, 2015 at 17:21
  • Why do you need so many variaibles? What are you doing? Commented Nov 18, 2015 at 17:22
  • It's easy to do: declare "filename_$newname=less_$newname.txt", but not a great idea. You don't know what variable names are actually defined. Commented Nov 18, 2015 at 17:23
  • 1
    This sounds like something you would want to use an array for instead of individual variables. (Possibly an associative array if you have bash 4+ and need to go from one name to another easily.) Commented Nov 18, 2015 at 18:15

1 Answer 1

1

Pretty sure you want something a little different (hopefully simpler) to meet the goal.

declare -A filename
for f in *
do
        if [ -f "$f" ]
        then
                b="${f%.*}"
                o="less_${b}.txt"
                filename["$b"]="$o"
                cp "$f" "$o"
        fi
done

declare -A creates an associative array -- which is a better solution than using a concatenated suffix. The test for -f makes sure we are dealing with only regular files (not directories). The ${f%.*} strips off the extension. cp copies the file to the new name.

Iterating over the collected file names is now easy:

for k in "${!filename[@]}"
do
        echo "${filename[$k]}"
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.