Home > front end >  Consider each line generated by a command as a line in a script
Consider each line generated by a command as a line in a script

Time:04-24

I have this simple script :

#!/bin/bash

dates_and_PID=$(ps -eo lstart,pid)

echo ${dates_and_PID::24}

And I would like each line to be cut at the 24th character. Nevertheless, it considers the variable dates_and_PID as a single line, so I only have one line that is generated. Whereas I would like it to be cut for each line.

I am practicing but the final goal would be to have the script change the dates from Mon Nov 11 2020 to 11/11/20.

Thank your for your help :)

CodePudding user response:

With awk and an array:

ps -eo lstart,pid \
  | awk 'BEGIN{
      OFS="/";
      m["Jan"]="01"; m["Feb"]="02"; m["Mar"]="03"; m["Apr"]="04";
      m["May"]="05";    # please complete remaining months yourself
    }
    {
      sub("..", "", $5);  # replace leading 20 from 2022 with nothing
      print $3, m[$2], $5
    }'

Output (e.g.):

24/04/22
24/04/22
24/04/22

CodePudding user response:

You need to iterate over the input line by line, instead of reading everything into a single variable. Something like this should do the trick:

#!/bin/bash

while read line; do
  echo "${line::24}"
done < <(ps -eo lstart,pid)
  • Related