2

I'm writing a script that needs to find an exact match in a file that is compatible with QNX and POSIX compliant Linux

more detail:

Im trying to find the user of a process so the original command I wrote was

user=$(ps -aux | awk '{print $1 " " $2}' | grep -w ${process} | awk '{}print $1')

which works perfectly in POSIX compliant Linux

however, QNX isn't totally POSIX compliant and grep -w isn't usable for my target...so I need to find an exact match without grep -w

  • I believe a single invocation of `awk` can do whatever you hope to achieve with `awk ... | grep ... | awk ...` which is almost always a poor structure. Please show sample output from your `ps` and explain what parts need to match what. Also consider replacing one if your 3 `qnx` tags with `awk`. – Mark Setchell Jul 25 '17 at 22:19
  • so my goal is to get the user of a process being given the process ID so I have to remove all the garbage values from the ps -aux command which is what the first awk is for (I awk for ID and user name only and remove all other numbers that can screw up the following grep -w) I then grep -w the ID ( I need exacts because you can have an ID of 11 and 1112 which regular grep will pull both) then I awk out only the user name which is saved to the variable... also thanks for the tip on the tags – Anthony Calandra Jul 26 '17 at 14:36
  • Yes, use a single `awk` with word delimiters like `awk '/\/ {do something}'` – Mark Setchell Jul 26 '17 at 16:13
  • @MarkSetchell – the `\<` and `\>` word boundary characters only work in GNU awk (gawk), which I doubt is available on QNX if GNU grep isn't available, but you can do `ps -aux |awk '$2=="'$process'"{print $1}'` – Adam Katz Jul 31 '17 at 17:33
  • Also, I'm pretty sure you can just do `ps u $process |awk 'NR>1{print $1}'`, but I don't know QNX's ps options. – Adam Katz Jul 31 '17 at 17:39

2 Answers2

1

I think you want to print field 1 if field 2 exactly matches something:

ps -aux | awk -v p=$process '$2==p{print $1}'
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
0

-w is not a valid POSIX option for grep, shouldn't be using that for an application that is supposed to be portable between POSIX systems. Could always just ps -p $1 -o user= ? What are you going to do with grep and awk in cases where the user may be the same as the process id?

v836
  • 111
  • 2
  • Thanks I honestly assumed -w was posix since it was grep...also im planning on not having users that are string of numbers like the ID's so I'm ignoring the possibility of it sort of... but Im just gonna put a warning that will pop if the situation occurs (this is only being used by engineers so they can handle the edge case if it occurs) – Anthony Calandra Jul 26 '17 at 19:52