Stéphane
Stéphane

Reputation: 506

Use awk to remove unwanted spaces

I have the following piece of code:

awk_cmd='{ if ($4 == '"$1"') { printf $0 } }'
printf "$(date +%s)$EPM_DB_SEP" >> "$EPM_RUN_DIR/$2.pid"
ps -e -o user,group,comm,pid,ppid,pgid,etime,nice,rgroup,ruser,time,tty,vsz,stat,rss,args |\
    awk "$awk_cmd" | sed 's/  */ /g' >> "$EPM_RUN_DIR/$2.pid"

Can I modify $awk_cmd to avoid using sed later to remove the unwanted spaces?

The awk version implied is the one coming with BusyBox v1.26.2

Upvotes: 0

Views: 62

Answers (3)

Stéphane
Stéphane

Reputation: 506

I’m adding another answer as I can’t edit the first one (I don’t understand why and contacted the site about that…). I’m giving more context and took into account Ed Morton’s comment. Also put "pid" in the first column.

filter_pid() { awk -v pid="$1" -v ORS= '$1 == pid{$1=$1; print}'; }

ps_store_current_info() {
    printf "$(date +%s)$EPM_DB_SEP" >> "$EPM_RUN_DIR/$2.pid"
    ps -e -o pid,ppid,user,group,comm,pgid,etime,nice,rgroup,ruser,time,tty,vsz,stat,rss,args |\
    filter_pid $1 >> "$EPM_RUN_DIR/$2.pid"
    printf "\n" >> "$EPM_RUN_DIR/$2.pid"
}

$EPM_DB_SEP equals | and $EPM_RUN_DIR points to a directory.

I well understand that doing this is not very clever because I won’t be able to later use the space as my (sub)field-separator but that’s really is another problem…

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203169

This is probably what you want:

function awk_cmd { awk -v pid="$1" -v ORS= '$4 == pid{$1=$1; print}'; }
printf "$(date +%s)$EPM_DB_SEP" >> "$EPM_RUN_DIR/$2.pid"
ps -e -o user,group,comm,pid,ppid,pgid,etime,nice,rgroup,ruser,time,tty,vsz,stat,rss,args |
    awk_cmd "$1" >> "$EPM_RUN_DIR/$2.pid"

but without sample input/output it's an untested guess.

Upvotes: 2

Stéphane
Stéphane

Reputation: 506

Very simple…

awk_cmd='{ if ($4 == '"$1"') { gsub("  *"," ",$0); printf $0 } }'
printf "$(date +%s)$EPM_DB_SEP" >> "$EPM_RUN_DIR/$2.pid"
ps -e -o user,group,comm,pid,ppid,pgid,etime,nice,rgroup,ruser,time,tty,vsz,stat,rss,args |\
    awk "$awk_cmd" >> "$EPM_RUN_DIR/$2.pid"

Upvotes: -1

Related Questions