Search code examples
bashcuttr

How to work around tr and cut not being available?


I don't have tr and cut available to use. This (extract) works with them on a Linux server:

disk_avail=$(df -k /var/tmp | tail -1 | tr -s ' ' | cut -d' ' -f4)  
pids=$(cat /var/tmp/$0.pid | tr -s ' ' | cut -d ' ' -f 2)  
while [ $count -le 4 ]  

..but when I try implement them on the device it says:

tr: not found
cut: not found
tr: not found
cut: not found
[: -lt: unexpected operator

Can anyone help me around this please?
I've just checked and sed and awk are available.
The device is a Juniper router running JunOS.
Outputs as requested:

% ls /bin/cut
ls: /bin/cut: No such file or directory
% ls /usr/bin/cut
ls: /usr/bin/cut: No such file or directory
%

Thank you for the awk suggestions below, I'll try them out soonest.

The awk solutions worked thanks!!


Solution

  • awk is normally available, so supposing you have it in your machine, this approach can help you solve the problem:

    df -k /var/tmp | tail -1 | tr -s ' ' | cut -d' ' -f4
    

    This means you want to get, from the last line of df -k, the 4th field.

    This is a equivalent:

    disk_avail=$(df -k /var/tmp | awk 'END {print $4}')
    

    We are taking advantage of awk being able to access to the last line when processing the END block. This way, you can print the last 4th field. Also, there is no need to combine tr -s' ' and cut, because awk does handle multiple spaces as one.


    Regarding this one:

    pids=$(cat /var/tmp/$0.pid | tr -s ' ' | cut -d ' ' -f 2)  
    

    this gets the 2nd field from /var/tmp/$0.pid. Similarly, you can use this awk:

    pids=$(awk '{print $2}' /var/tmp/$0.pid)
    

    Regarding the problem with while [ $count -le 4 ], take into account what Keith Thompson comments:

    The [: -lt: unexpected operator is probably because $count is empty because of the earlier errors. Quoting the argument would avoid that: while [ "$count" -le 4 ]