0

I'm trying to extract the process numbers starting with the number 3.

When using ps | sed "/^\s\+3/", I get an error message : sed: -e expression #1, char 8: missing command

I then added a global flag : ps | sed "/^\s+3/g" which succeeds but instead of showing me all matches, it removes all the matches found.

This is the unchanged output :

  PID TTY          TIME CMD
 3128 pts/8    00:00:00 bash
 5279 pts/8    00:00:00 ps
 5280 pts/8    00:00:00 sed

In the end, this is the output I get : PID TTY TIME CMD

 5219 pts/8    00:00:00 ps
 5220 pts/8    00:00:00 sed
Corb3nik
  • 1,177
  • 7
  • 26

2 Answers2

2

You need to add -n parameter to print the lines which matches a particular pattern. And note that, basic sed won't support the pattern \s (which is used for matching whitespaces).

ps | sed -n '/^ *3/p'

OR

ps | sed -n '/^[[:blank:]]*3/p'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • From man pages, -n is : suppress automatic printing of pattern space. Isn't suppressing the contrary of what we want here? (Btw this works, but I have a hard time understanding it) – Corb3nik Nov 06 '14 at 14:06
  • 1
    sed reads the input line by line. so it appends line to pattern space before doing any operation on that particular line. S if `/^ *3/` matches the line which is present in the ps, then -n and p causes automatic printing of those lines. – Avinash Raj Nov 06 '14 at 14:10
  • Another way is `ps | sed '/^ *3/!d'` i tried adding to the answer in an edit(as it is too similar to be an answer on it's own and also the question is closed) but it got rejected :( –  Nov 06 '14 at 14:55
2

It sounds like sed isn't really the best tool for the job. Try awk:

ps | awk '$1 ~ /^3/'

This prints all lines whose first column begins with 3.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141