Reputation: 458
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)
Upvotes: 1
Views: 1490
Reputation: 52211
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")'
Upvotes: 4
Reputation: 43039
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:
Upvotes: 2