如何用grep匹配含三位可变数字的进程路径?
Let's break down why your original command isn't working and fix it right away.
What's Wrong with Your Current Command?
Your attempt:
sudo ps axu | grep "psd_folr/rcerr-m-deve-udf-'^[0-9]$'/bin/magt queue"
Has two critical issues:
- Incorrect regex for 3-digit numbers:
'^[0-9]$'matches a single digit that's the entire line (thanks to^and$), not three consecutive digits in the path segment. Also, wrapping the regex part in single quotes inside double quotes makes the shell treat those quotes as literal characters, so grep isn't parsing the regex correctly. - Misplaced anchors:
^and$anchor the match to the start/end of the entire line, which isn't what you want—you need to match a segment within the process path.
Correct Commands to Use
There are two reliable ways to get the match you need:
Option 1: Basic Grep (no extended regex flag)
Use escaped curly braces to specify exactly 3 digits:
sudo ps axu | grep "psd_folr/rcerr-m-deve-udf-[0-9]\{3\}/bin/magt queue"
[0-9]\{3\}: Matches exactly three consecutive digits (the backslash escapes the curly braces for basic grep syntax).
Option 2: Extended Grep (cleaner syntax)
Add the -E flag to use extended regex, which lets you skip escaping curly braces:
sudo ps axu | grep -E "psd_folr/rcerr-m-deve-udf-[0-9]{3}/bin/magt queue"
This does the same thing as option 1, but the regex is more readable.
Avoid Matching the Grep Process Itself
If you want to exclude the grep command itself from the results, append | grep -v grep:
sudo ps axu | grep -E "psd_folr/rcerr-m-deve-udf-[0-9]{3}/bin/magt queue" | grep -v grep
Or use pgrep for a cleaner approach (it automatically excludes itself):
sudo pgrep -af -E "psd_folr/rcerr-m-deve-udf-[0-9]{3}/bin/magt queue"
-a: Shows the full command line-f: Matches against the full command line instead of just the process name-E: Enables extended regex
Example Match
For your sample process path:
/var/www/vhosts/rcsdfg/psd_folr/rcerr-m-deve-udf-172/bin/magt queue:consumers:start customer.import_proditns --single-thread --max-messages=1000
All the correct commands above will match this line, since 172 is a 3-digit number in the expected path segment.
内容的提问来源于stack exchange,提问作者NKumar

