0

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.

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
bkbn
  • 41
  • 4
  • 3
    Are you looking for something like that? `ps -eo lstart,pid | cut -b 1-24` – Cyrus Apr 23 '22 at 22:07
  • Do you want `dd/mm/yy` or `mm/dd/yy`? November 11 is a somewhat inappropriate example. – Cyrus Apr 23 '22 at 22:24
  • If you want only the first column, why not `ps -eo lstart`? – Weihang Jian Apr 24 '22 at 02:42
  • In part, you're running into [I just assigned a variable, but `echo $variable` shows something else!](https://stackoverflow.com/questions/29378566) -- expansions need to be quoted for newlines to be treated as part of the literal data rather than as word separators. – Charles Duffy Apr 24 '22 at 03:17

2 Answers2

0

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)
Cyrus
  • 84,225
  • 14
  • 89
  • 153
Andrew Vickers
  • 2,504
  • 2
  • 10
  • 16
  • Consider making it `while IFS= read -r line; do` -- `IFS=` stops leading and trailing whitespace from being silently removed; `-r` prevents backslashes from being consumed. Using both together means your `$line` actually contains the line precisely as it was in input. – Charles Duffy Apr 24 '22 at 03:19
  • Both very valid additions. I didn’t want to over-complicate the answer, given the questioner’s obvious unfamiliarity with the language. – Andrew Vickers Apr 25 '22 at 10:45
0

You can pipe stdout to while loop:

ps -eo lstart,pid | while read line; do
  echo "${line::24}"
done
Weihang Jian
  • 7,826
  • 4
  • 44
  • 55
  • The answer by Andrew Vickers avoids the bug described in [BashFAQ #24](https://mywiki.wooledge.org/BashFAQ/024), which this answer is subject to. Doesn't matter if all you're trying to do is `echo`, does matter if one starts trying to set variables inside the loop. – Charles Duffy Apr 25 '22 at 12:28