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)
1
  • 1
    Commas in array doesn't really make sense. What is your idea behind having it? Did you try anything to solve the problem? Commented Feb 9, 2017 at 6:39

2 Answers 2

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")'
Sign up to request clarification or add additional context in comments.

Comments

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:

6 Comments

There is nothing wrong with adding quotes around parameter expansion, in-fact it is most efficient.
In fact, it is required for handling files with spaces. Corrected, thanks for noticing it, @Inian.
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: So then please post a improved version, so that others can learn from it. Just complaining is not a high-quality comment.
I updated the answer based on @Inian's comment. It is good to see his answer as well.
|

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.