Home > Back-end >  Column without last characters with awk and printf
Column without last characters with awk and printf

Time:11-24

I have this script:

#!/bin/bash

f_status () {
        systemctl list-units | grep $1 | awk '{ printf("SERVICE STATUS:  %-25s \t %s \t %s \t %s\n",$1,$2,$3,$4) }'
}

f_line() {
        echo "-------------------------------------------------------------------------------------------"
}

echo ""
f_line
f_status "cron"
f_status "ssh"
f_line

This script gives me such a result:

-------------------------------------------------------------------------------------------
SERVICE STATUS:  cron.service                    loaded          active          running
SERVICE STATUS:  ssh.service                     loaded          active          running
-------------------------------------------------------------------------------------------

and I search how to remove ".service" from 3d column.

I tried with substr($i, 0, -8) and ${1:-8}

Does anyone have any idea how to get rid of 8 characters from the end to make it look like this:

-----------------------------------------------------------------------------------
SERVICE STATUS:  cron                    loaded          active          running
SERVICE STATUS:  ssh                     loaded          active          running
-----------------------------------------------------------------------------------

CodePudding user response:

You never need grep when you're using awk since grep 'foo' file | awk '{print 7}' can be written as just awk '/foo/{print 7}' file.

Rather than counting characters, just remove everything starting from the last .:

systemctl list-units |
awk -v tgt="$1" '
    {
        svc = $1
        sub(/\.[^.]*$/,"",svc)
    }
    svc == tgt {
        printf "SERVICE STATUS:  %-25s \t %s \t %s \t %s\n",svc,$2,$3,$4
    }
'

I also tightened up your comparison to avoid false matches if called with a service name that's a subset of some other service name or contains regexp metachars like ..

CodePudding user response:

You need to compute end position based on string length, consider following simple example, let file.txt content be

cron.service
ssh.service

then

awk '{print substr($1,1,length($1)-8)}' file.txt

output

cron
ssh

Explanation: arguments for substr are string, start position, end position, length return number of characters in string.

(tested in gawk 4.2.1)

CodePudding user response:

you can use gsub funtion in awk,like the following:

 systemctl list-units | grep 'cron' | awk '{gsub(".service","",$1); printf("SERVICE STATUS:  %-25s \t %s \t %s \t %s\n",$1, $2 ,$3,$4) }'
SERVICE STATUS:  crond                       loaded      active      running
  • Related