How to run any linux command inside AWK command ?

Today we will look at an interesting tip how to run a linux command inside the awk command.

For this trick, we will assign the command to a variable, say cmd and then we will send this command to print which displays its output on shell.

Lets see its syntax.

# awk -v cmd='' '{print | cmd}' 
OR
# awk -v cmd='' '{print | cmd}'  ### Press return two times to have null filename

Running Linux command inside awk

### Without mentioning file, press return two times
[root@ngelinux ~]# awk -v cmd='df -h' '{print | cmd}'
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        20G   11G  8.2G  56% /
tmpfs           504M   72K  504M   1% /dev/shm
.host:/         844G  629G  216G  75% /mnt/hgfs

### When mentioning file.
[root@ngelinux ~]# awk -v cmd='df -h' '{print | cmd}' /proc/cpuinfo 
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        20G   11G  8.2G  56% /
tmpfs           504M   72K  504M   1% /dev/shm
.host:/         844G  629G  216G  75% /mnt/hgfs
[root@ngelinux ~]#

Leave a Reply

Your email address will not be published.