There are several issues with your code.
- The first important thing to remember is that since your
awk
program is enclosed in single quotes (which is recommended), no shell parameter expansions take place, and your statement print $[i]
will not work. See this exhaustive Q&A on StackOverflow on how to use shell parameter in awk
programs.
- Even so, an
awk
field whose number is stored in a (awk
) variable n
would be addressed via $n
, not $[n]
.
- You assign the variables
val1
to val4
but never actually use them, so the first part of your script example doesn't do anything.
- Finally, to dereference an array variable, you have to state
${val[i]}
, not $val[i]
(which would print the content of the variable $val
- the empty string - followed by the fixed string [i]
).
There are also several inefficiencies such as the repeated call to awk
and (as far as I can tell) a failure to address the issue of the leading Thread
in your example input when using just /
as field separator.
To address these issues, and since the relevant values do not contain whitespace in your example, try the following:
#!/bin/bash
val=( $(awk '/^Thread/{n=split($2,a,/\//); for (i=1;i<=n;i++) printf("%s%s",a[i],OFS)}' Threadout.txt) )
for i in ${!val[@]}
do
echo "${val[i]}"
done
- The
awk
call will split the second "field" of the line Thread 1/1/25/100
, namely the 1/1/25/100
part at the /
into the array a
and print all entries of the array, separated by OFS
(which defaults to space).
- The shell script will take the output of that
awk
program and - since it is a space-separated list of tokens - assign the individual tokens to an array variable val
via the val=( ... )
statement.
- It will then iterate over the array indices and print the array values.
You may want to read into bash arrays a little further in the GNU Bash Reference Manual, or GreyCat&Lhunath's Bash Guide. I would also recommend you to take a look at shellcheck to debug your shell scripts.
Threadout.txt
. Does it really only contain the lineThread 1/1/25/100
?