[英]How to print an array originated from a brace expansion command in bash scripting?
#!/bin/bash
declare -a arr=({1..$(wc mylist.txt | cut -d " " -f 3)})
for i in "${arr[@]}";
do
echo $i;
done
Basically what i'm trying to do is set an array using a brace expansion command.基本上我想要做的是使用大括号扩展命令设置一个数组。
The command is:命令是:
wc mylist.txt | cut -d " " -f 3
In short what this command does is return the number of lines of a file, but it will bring other outputs that i don't need besides the actual number.简而言之,这个命令的作用是返回文件的行数,但它会带来除实际数字之外我不需要的其他输出。 So I use cut afterwards to get the actual number i need on the wc command, which in this case is 7.所以我之后使用 cut 来获取我在 wc 命令上需要的实际数字,在本例中为 7。
So the brace expansion i use here (in my understanding) should bring me the number 1 to 7, like this:所以我在这里使用的大括号扩展(在我的理解中)应该给我带来数字 1 到 7,如下所示:
declare -a arr=({1..7})
which should translate into a line like this:这应该转化为这样的一行:
declare -a arr=(1 2 3 4 5 6 7)
. declare -a arr=(1 2 3 4 5 6 7)
。
When i try to print this array, inside the for-loop block, i was hopping it would get me an output like this:当我尝试在for循环块内打印这个数组时,我正在跳跃它会给我一个像这样的output:
1
2
3
4
5
6
7
Instead this is what i'm getting:相反,这就是我得到的:
{1..7}
How can i get the right output?我怎样才能得到正确的 output?
Thank you M. Nejat Aydin and markp-fuso.谢谢 M. Nejat Aydin 和 markp-fuso。 Both your suggestions worked.你的两个建议都奏效了。
arr=($(seq $(wc -l < mylist.txt)))
or或者
declare -a arr=( $(awk '{print FNR}' mylist.txt) )
With some adjustments, your code may behave as expected.通过一些调整,您的代码可能会按预期运行。
wc
command takes an -l
option for line count. wc
命令采用-l
选项来计算行数。cut
targets the first field of that wc
command output. cut
的目标是该wc
命令 output 的第一个字段。#!/bin/bash
total=$(wc -l mylist.txt | cut -d " " -f 1)
declare -a arr=( $(seq 1 "$total") )
for i in "${arr[@]}"
do
echo "$i";
done
1
2
3
4
5
6
7
Brace expansion didn't work for me either.大括号扩展对我也不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.