10

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
lonestar21
  • 1,113
  • 2
  • 13
  • 23

2 Answers2

8

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
Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59
jordanm
  • 33,009
  • 7
  • 61
  • 76
  • For the all awk solution it doesn't convert correctly. Numbers are printed as their digits, while letters are converted to '0'. I'm looking to convert ASCII values to integers. – lonestar21 Jun 27 '12 at 19:20
  • 2
    Or you can export the function (`export -f`) and *not* make the shell interactive. – Dennis Williamson Jun 27 '12 at 22:01
0

In the trivial case, you can use /usr/bin/printf:

xargs -I {} /usr/bin/printf '%d' "'{}"
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439