3

I have a files multiple file path for backup purpose ,now i want to filter it based on ".csv " fromat. I have tried this.

filesall=(/home/abc/allfiles/*)
files=$((${filesall[@]}|grep -F ".csv"))
files=$(${filesall[@]}|grep -oe "*.csv")

but unable to extract .csv files from $filesall . I know i can achieve it like this

files=(/home/abc/allfiles/*.csv)

any suggestion ,how can i get all .csv files from filesall.Thanks.

2 Answers 2

1

This is really not the best way to do this. Why parse the array? A simpler approach would be something like:

path=/home/abc/allfiles
filesall=(${path}/*)
files=(${path}/*.csv)

If you insist on doing it your way, you would have to do something like:

files=($(for file in "${filesall[@]}"; do [[ $file =~ \.csv$ ]] && echo $file; done))

or

files=($(printf "%s\n" "${filesall[@]}" | grep '\.csv$'))

But both of the above break if any of your file names contain whitespace. (They can be made to work with spaces if you precede them with saveIFS="$IFS"; IFS=$'\n' and follow them with IFS="$saveIFS", but they still break on newline.)

6
  • If we changed your last command to $(printf "%s\0" "${filesall[@]}" | grep -z '\.csv$') (to handle file names that contain whitespace), how could we get the result into array correctly? Would setting IFS to \0 do that? Commented Sep 12, 2014 at 16:47
  • @G-Man no idea. I thought I could get it to work but couldn't manage it. Probably because the Right Way© is to use a glob instead.
    – terdon
    Commented Sep 12, 2014 at 16:59
  • @terdon Thanks for your reply ,how can i read files as array ? files contain all the concatenated csv files.
    – Aashu
    Commented Sep 19, 2014 at 9:31
  • @Aashu what do you mean? All these methods read the files into an array. Do you want to read the contents of the files?
    – terdon
    Commented Sep 19, 2014 at 11:53
  • @terdon Sorry, i was ssaying regarding files=($(printf "%s\n" "${filesall[@]}" | grep '\.csv$')) this expression.
    – Aashu
    Commented Sep 19, 2014 at 14:25
0

Building on terdon’s answer, here’s one that seems to work:

filesall=(all files)
files=(); for file in "${filesall[@]}"; do [[ $file =~ \.csv$ ]] && files+=("$file"); done

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.