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!

fedorqui
  • 275,237
  • 103
  • 548
  • 598
user7408924
  • 97
  • 2
  • 9

1 Answers1

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
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 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 Jan 19 '17 at 15:52
  • @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! – fedorqui Jan 19 '17 at 15:54