1

I'd like to extract the names of all files with one specific extension (.com) without their extensions from the current directory and store them in an array.

This is what I tried:

test=$((*.com) | sed 's/.com//g')

I get the error

zsh: permission denied: 1butene.com

1butene.com is a file I have.

Thanks for your help!

1 Answer 1

0

You are currently storing a set of names and then piping to sed. When the glob is expanded this becomes a command on the form:

1butene.com xxxx | sed 's/.com//g'

Which is obviously not something allowed, as 1butene.com is not a command by itself.


What you have to do is to

1) store the data,
2) perform the cleaning.

For this we have good news! You can perform Shell parameter expansion on arrays!

This way you can store the data in an array:

names=(*.com)

And then perform the replacement in all of them by just extracting its name, without the extension:

printf "%s\n" "${names[@]%.*}"

If you then want to change values of bash array elements without loop, just use the syntax

new_array=("${names[@]%.*}")

Sample:

$ touch a{1..3}.{sql,com}
$ com_names=(*com)
$ printf "%s\n" "${com_names[@]}"
a1.com
a2.com
a3.com
$ printf "%s\n" "${com_names[@]%.*}"
a1
a2
a3
b=("${com_names[@]%.*}")         # assign to a new array
$ printf "%s\n" "${b[@]}"
a1
a2
a3
Sign up to request clarification or add additional context in comments.

2 Comments

OK, that seems to work somehow. But how do I store these names in the array? If I do test=(*.com) and then test=${"%\n" "${names[@]%.*}"} $test is empty
@user7408924 see the last part of my explanation, before the Sample section: var=("${ ... [@]%.*}"). Also, try not to use the name test for variables, since it is a command itself!

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.