Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a user defined bash function in xargs [duplicate]

Tags:

bash

xargs

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
like image 700
lonestar21 Avatar asked Jun 27 '12 18:06

lonestar21


1 Answers

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
like image 135
jordanm Avatar answered Oct 20 '22 18:10

jordanm