Using sed to print and replace text in the output of the ps command

9,058

Solution 1

1. How to print the tty column from ps with sed?

ps | sed 's/ *[^ ]* *\([^ ]*\).*/\1/'

Explanations

I'll use for the space character.

  • s/A/B/substitute A by B one time per line
  • ␣* – 0 or more spaces
  • [^␣]* – 0 or more characters that are not (^) a space
  • \(…\) – a group, everything inside the escaped brackets gets saved as \1 as it's the first group here
  • .* – 0 or more occurences of any character except newline
  • \1 – calls the afore saved group

Alternative ways

ps -o tt
ps | awk '{print $2}'

2. How to replace the TTY row with “terminal”?

ps | sed '2,$s/\([^0-9 ][^ ]*\)/terminal/'

Explanations

  • 2,$ – process every line from the second to the last (so leave the first line out) – I assumed you want the TTY heading to stay, if not just omit this.
  • [^0-9␣] – any one character except one of these: 0123456789␣
  • terminal – the string terminal

Alternative way

ps | sed '2,$s/\([0-9 ]*\)[^ ]*/\1terminal/'
ps | awk '{$2="terminal";print}' # change every line
ps | awk '{if(NR>1){$2="terminal"};print}' # omit first line

Solution 2

ps has lots of options - you shouldn't need to parse it to get the output you want (the same applies to many commands, but this is especially unhelpful with ps because the output you get will include the program parsing the output...)

If you really want to though, you can parse it to print the TTY column with sed like this:

$ ps | sed -r 's/^ +[^ ]+ +([^ ]+) .*/\1/'
TTY
pts/4
pts/4
pts/4

Notes

  • -r use extended regex
  • s/old/new/ replace old with new
  • ^ start of line
  • + one or more of the preceding character
  • ([^ ]+) save some non-space characters later
  • .* any number of any characters
  • \1 back-reference to the saved pattern

You can probably replace the pts text like this:

$ ps | sed 's:pts/\?[0-9]*:terminal:'
  PID TTY          TIME CMD
 3379 terminal    00:00:00 bash
 3466 terminal    00:00:00 ps
 3467 terminal    00:00:00 sed

Notes

  • s:old:new: replace old with new
  • \? zero or one of the preceding character
  • [0-9]* zero or more digits
Share:
9,058

Related videos on Youtube

Ktgvb
Author by

Ktgvb

Updated on September 18, 2022

Comments

  • Ktgvb
    Ktgvb over 1 year
    1. How to print the tty column from ps via sed?

        PID      TTY        TIME CMD
      13445    pts/7    00:00:00 bash
      15286    pts/7    00:00:00 sort
      15336    pts/7    00:00:00 sort
      18896    pts/7    00:00:00 sed
      19387    pts/7    00:00:00 ps
      
    2. How to replace the rows of TTY with 'terminal'?

    • Zanna
      Zanna over 6 years
      what text do you actually want to replace?
    • muru
      muru over 6 years
      Why via sed? Why not ps -o tty?