The following script is supposed to concatenate multiple csv files in a path specified in the first argument into a single csv file specified in the second argument

set -x
set -v

# First the headers:
head -n1 ${globbing_pattern}([1,1]) > $output_file

# Now concatenate everything:
find ${globbing_pattern} -print0 | xargs -0 cat >> $output_file

I would like to call this script with:

my_script '/some/path/*.csv' output.csv

but it doesn't work. I get:

find: /some/path/*.csv: No such file or directory



zsh doesn't expand globbings in variables unless told to with the $~PATTERN syntax.

I would write it:

#! /bin/sh -
head -n -- "$1"
cat -- "$@"

And use it as:

my-script /some/path/*.csv > output.csv

That way, you can still post-process the output of your script, and the globbing is done in the user's shell. Now if you do want the globbing to be done by the script, for instance to overcome the "too many args" limit or because you do want a zsh globbing regardless of the shell of the users, and if you do want the script to write the output file (for instance to prevent it from coming up as an input file, or not to create it if there's no input file), you'd need to write it:

#! /bin/zsh -
files=(${~1?}) output=${2?}
head -n 1 -- $files[1]
printf '%s\0' $files | xargs -r0 cat -- > $output

Or with zsh's zargs:

#! /bin/zsh -
files=(${~1?}) output=${2?}
head -n 1 -- $files[1]
autoload zargs
zargs --eof= -- $files '' cat -- > $output

Now, I'm not sure that's really what you want as that means the "header" will be displayed twice. Also note that files called - can be a problem.

Maybe you actually want (with GNU tail):

#! /bin/zsh -
setopt extendedglob
files=(${~1?}) output=${2?}
cat < $files[1]
autoload zargs
zargs --eof= -- $files[2,-1] '' tail -qn +2 -- > $output

(here using extendedglob so you benefit from the full zsh globbing).


find: /some/path/*.csv:

Find sytanx is wrong.

To find all files in given folder tree that end with .csv:

find /some/path -name "*.csv"

So, you need to separate location and the name of the file.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.