1

I have files like:

abc.json
xyz.json
pdf.json

I would like to get the result like this without "json" extension:

somearray=(abc, xyz, pdf)
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
MMA
  • 408
  • 3
  • 7
  • 19
  • 1
    Commas in array doesn't really make sense. What is your idea behind having it? Did you try anything to solve the problem? – Inian Feb 09 '17 at 06:39

2 Answers2

4

You can get your files into an array with globbing, then remove the extensions with parameter expansion:

$ arr=(*.json)
$ declare -p arr
declare -a arr='([0]="abc.json" [1]="pdf.json" [2]="xyz.json")'
$ arr=("${arr[@]%.json}")
$ declare -p arr
declare -a arr='([0]="abc" [1]="pdf" [2]="xyz")'
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
2

You can do it simply with this:

some_array=( $(ls | sed 's/.json$//') )

Or, if you are only looking for .json files, then:

some_array=( $(ls | grep '.json$' | sed 's/.json$//') )

The method above is not safe if you have any files that have white space or wildcard (*) in them.

If you are using Bash, then you can use parameter expansion to take the extension out. And this approach is more robust than the earlier ones - it handles files with white spaces or wildcard gracefully:

declare -a some_array
for file in *.json; do
  some_array+=( "${file%.json}" )
done

See these posts:

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • 1
    There is nothing wrong with adding quotes around parameter expansion, in-fact it is most efficient. – Inian Feb 09 '17 at 06:37
  • In fact, it is required for handling files with spaces. Corrected, thanks for noticing it, @Inian. – codeforester Feb 09 '17 at 06:38
  • 1
    You can do far better than parsing output of `ls` and using `grep/sed` back to back makes it worse. There is every chance of word-splitting in the first two cases. Better don't recommend the first two approaches. – Inian Feb 09 '17 at 06:43
  • 1
    @Inian: So then please post a improved version, so that others can learn from it. Just complaining is not a high-quality comment. – ckruczek Feb 09 '17 at 06:47
  • I updated the answer based on @Inian's comment. It is good to see his answer as well. – codeforester Feb 09 '17 at 06:48
  • @ckruczek: I would have done the same thing as the native `bash` implementation of the above answer. That's why I upvoted it. And I have every right to critique on the answer if it is less efficient as long as it is constructive – Inian Feb 09 '17 at 06:48