using a user defined bash function in xargs

lonestar21 picture lonestar21 · Jun 27, 2012 · Viewed 8.3k times · Source

I have this self-defined function in my .bashrc :

function ord() {
  printf '%d' "'$1"
}

How do I get this function to be used with xargs ?:

cat anyFile.txt | awk '{split($0,a,""); for (i=1; i<=100; i++) print a[i]}' | xargs -i ord {}
xargs: ord: No such file or directory

Answer

jordanm picture jordanm · Jun 27, 2012

First, your function only uses 1 argument, so using xargs here will only take the first arg. You need to change the function to the following:

ord() {
   printf '%d' "$@"
}

To get xargs to use a function from your bashrc, you must spawn a new interactive shell. Something like this may work:

awk '{split($0,a,""); for (i=1; i<=100; i++) print a[i]}' anyFile.txt | xargs bash -i -c 'ord $@' _

Since you are already depending on word splitting, you could just store awk's output in an array.

arr=(awk '{split($0,a,""); for (i=1; i<=100; i++) print a[i]}' anyFile.txt)
ord "${arr[@]}"

Or, you can use awk's printf:

awk '{split($0,a,""); for (i=1; i<=100; i++) printf("%d",a[i])}' anyFile.txt