user2027303 user2027303 - 9 months ago 41
Linux Question

How can I pass all arguments with xargs in middle of command in linux

I want to pass all the files as a single argument on linux but I am not able to do that.

This is working

ls | sort -n | xargs -i pdftk {} cat output combinewd2.pdf

This passes a single argument per command, but I want all in one command.


This is one way to do it

pdftk $(ls | sort -n) cat output combinewd2.pdf

or using backtick

pdftk `ls | sort -n` cat output combinewd2.pdf

As pointed out in the comments this will not work on filenames containing spaces. In that case you could use eval

eval pdftk $(while IFS= read -r file; do
    echo \"$file\"
done < <(ls | sort -n)) cat output combinewd2.pdf

Suppose there are two files named " 0 foo " and " 1 bar " then the result of eval would be the desired command, with the file names in double quotes:

pdftk " 0 foo " " 1 bar " cat output combinewd2.pdf

If the filenames might contain newlines, then use find command, see discussion by @joeytwiddle in the comments of @andrewdotn's answer. The following solution also handles file names with double quotes using the sed command to escape double quotes:

eval pdftk $(while IFS= read -r -d '' file; do
    echo \"$file\"
done < <(find . -maxdepth 1 -type f -print0 | \
    sed 's/"/\\"/g'| sort -zn)) cat output combinewd2.pdf