linux - 从 bash 中的文件行获取字符串

标签 linux bash ubuntu grep cut

我在文件中有这些行:

postgres  2609 21030  0 12:49 ?        00:00:00 postgres: postgres postgres [local] idle in transaction                                                                     
postgres  2758 21030  0 12:51 ?        00:00:00 postgres: postgres postgres [local] idle in transaction                                                                     
postgres 28811 21030  0 09:26 ?        00:00:00 postgres: postgres postgres [local] idle in transaction                                                                     
postgres 32200 21030  0 11:40 ?        00:00:00 postgres: postgres postgres [local] idle in transaction                                                                     
postgres 32252 21030  0 11:41 ?        00:00:00 postgres: postgres postgres [local] idle in transaction                                                                     

我需要分开第二列值来处理它们。我已经完成了这段代码:

pid=$(cat idle_log.txt | cut -d" " -f2)
echo $pid

但它只给了我 28811 32200 32252 结果。如你所见,列表中没有 2609 2758 的踪迹,我也想得到它们。 我还想在提取 pids 后对它们进行计数。 我用过:

npid=$(grep -o " " <<< $pid | grep -c .)

它为 28811 32200 32252 的结果返回 2 我需要它返回 3 作为进程数。 最后我想逐行处理一些事情,就像在 while 循环中一样,但是命令的输出立即返回结果,我不能以循环格式逐个处理它们。

谢谢大家的帮助。

最佳答案

您可以使用 tr 压缩空格,然后使用 cut 获取第二个空格分隔的字段:

tr -s ' ' <idle_log.txt | cut -d' ' -f2

或者awk:

awk '{ print $2 }' idle_log.txt

或者sed:

sed -r 's/^[^[:blank:]]+[[:blank:]]+([^[:blank:]]+)(.*)/\1/' idle_log.txt

或者grep:

grep -Po '^[^\s]+\s+\K[^\s]+' idle_log.txt

稍后要使用/计算它们,请使用数组:

pids=( $(tr -s ' ' <idle_log.txt | cut -d' ' -f2) )

num_of_pids="${#pids[@]}"

$ printf '%s\n' "${pids[@]}" 
2609
2758
28811
32200
32252

示例:

$ tr -s ' ' <file.txt | cut -d' ' -f2 
2609
2758
28811
32200
32252

$ awk '{ print $2 }' file.txt        
2609
2758
28811
32200
32252

$ sed -r 's/^[^[:blank:]]+[[:blank:]]+([^[:blank:]]+)(.*)/\1/' file.txt
2609
2758
28811
32200
32252

$ grep -Po '^[^\s]+\s+\K[^\s]+' file.txt
2609
2758
28811
32200
32252

关于linux - 从 bash 中的文件行获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37250691/

相关文章:

ios - 是否可以在 ubuntu 中为 ios 开发设置 cordova?

bash - 如何使 .bashrc 别名在 vim shell 命令中可用? (:! ...)

python - 使用 CDLL lib(或其他)在 Debian 64 位上使用 python 访问 32 位

linux bash - ps uax - 看不到运行脚本?

linux - getopts 用于标志和选项解析

linux - 使用 sed 或 awk 替换匹配后的行

bash - 如何为终端制作动画 bash shell 提示符?

python - 如何在 Linux 上安装 Python 包,以便可以通过已经运行的 PostgreSQL 13 plpython3u 扩展找到它?

c++ - Tcl fileevent 在 64 位版本的 Tcl 上挂起

linux - 将函数指针从内核驱动程序传递到管理程序