我在文件中有这些行:
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/