如何将命令的输出分配到数组中? [英] How do I assign the output of a command into an array?

查看:40
本文介绍了如何将命令的输出分配到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 grep 的结果分配给一个数组...例如

I need to assign the results from a grep to an array... for example

grep -n "search term" file.txt | sed 's/:.*//'

这导致了一堆带有行号的行,其中找到了搜索词.

This resulted in a bunch of lines with line numbers in which the search term was found.

1
3
12
19

将它们分配给 bash 数组的最简单方法是什么?如果我只是将它们分配给一个变量,它们就会变成一个以空格分隔的字符串.

What's the easiest way to assign them to a bash array? If I simply assign them to a variable they become a space-separated string.

推荐答案

要将命令的输出分配给数组,您需要在数组分配中使用命令替换.对于一般命令 command 这看起来像:

To assign the output of a command to an array, you need to use a command substitution inside of an array assignment. For a general command command this looks like:

arr=( $(command) )

在 OP 的示例中,这将显示为:

In the example of the OP, this would read:

arr=($(grep -n "search term" file.txt | sed 's/:.*//'))

内部 $() 运行命令,而外部 () 导致输出为数组.这样做的问题是当命令的输出包含空格时它将不起作用.为了解决这个问题,您可以将 IFS 设置为 \n.

The inner $() runs the command while the outer () causes the output to be an array. The problem with this is that it will not work when the output of the command contains spaces. To handle this, you can set IFS to \n.

IFS=$'\n' arr=($(grep -n "search term" file.txt | sed 's/:.*//'))

您还可以通过对数组的每个元素执行扩展来消除对 sed 的需要:

You can also cut out the need for sed by performing an expansion on each element of the array:

arr=($(grep -n "search term" file.txt))
arr=("${arr[@]%%:*}")

这篇关于如何将命令的输出分配到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆