简体   繁体   中英

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.

So the brace expansion i use here (in my understanding) should bring me the number 1 to 7, like this:

declare -a arr=({1..7})

which should translate into a line like this:

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:

1
2
3
4
5
6
7

Instead this is what i'm getting:

{1..7}

How can i get the right output?

Thank you M. Nejat Aydin and 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.

Adjustments:

  1. The wc command takes an -l option for line count.
  2. The cut targets the first field of that wc command output.
  3. Assign that value to a variable, but that's perhaps just a style issue.
#!/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

Output:

1
2
3
4
5
6
7

Brace expansion didn't work for me either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM