bash 在 shell 中解析 ps 和 grep 输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18088224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:09:31  来源:igfitidea点击:

Parsing ps and grep output in shell

linuxbashshellgrepcgi

提问by Jeremy

I get the following message when I do a "ps -ef | grep port"

当我执行“ps -ef | grep port”时,我收到以下消息

apache    6215     1  0 11:20 ?        00:00:00 perl /scripts/myscript.pl -sn 4123E -sku HSME01-HW -port 8

Is there a way to parse the following:

有没有办法解析以下内容:

  • start time (11:20)
  • sn (4123E)
  • sku (HSME01-HW)
  • port (8)
  • 开始时间(11:20)
  • SN (4123E)
  • sku (HSME01-HW)
  • 端口 (8)

回答by Ansgar Wiechers

You can use awkfor both filtering and parsing:

您可以awk用于过滤和解析:

ps -ef | awk '/[p]ort/ {printf "start time: %s\nsn: %s\nsku: %s\nport: %s\n", , , , $NF}'

As glenn Hymanman pointed out in the comments the square brackets in the filter string prevent the expression from matching the filter string itself in the process list.

正如 glenn Hymanman 在评论中指出的,过滤字符串中的方括号会阻止表达式匹配进程列表中的过滤字符串本身。

回答by saeedgnu

Since the question is tagged as bash, using bash-only solutions (no awk or perl) is preferred...

由于问题被标记为bash,因此首选使用 bash-only 解决方案(无 awk 或 perl)...

LINE='apache    6215     1  0 11:20 ?        00:00:00 perl /scripts/myscript.pl -sn 4123E -sku HSME01-HW -port 8'

## Convert string to bash array
ARR=($LINE)

echo "start time (${ARR[4]})"
echo "sn (${ARR[10]})"
echo "sku (${ARR[12]})"
echo "port (${ARR[14]})"

## How to save the value?
START_TIME=${ARR[4]}