Not sure about why you need awk, but you can add the -a
flag to read
so you get an array. Assuming the field/columns that you're talking about is delimited/separated by a space.
read -rp "Enter args: " -a input
printf 'Your 3rd argument was %s\n' "${input[2]}"
- Just remember bash arrays starts at zero index.
You can loop through the input.
read -rp "Enter args: " -a input
for ((i=0; i<${#input[@]}; i++)); do
printf 'Your %d argument was %s\n' "$i" "${input[$i]}"
done
Or like this
read -rp "Enter args: " -a input
for i in "${!input[@]}"; do
printf 'Your %d argument was %s\n' "$i" "${input[$i]}"
done
But here is what I would do using awk.
read -rp "Enter args: "
nth=$(awk '{\*Do some stuff with fields*\; print $3}' <<< "$REPLY")
printf 'Your 3rd argument was %s\n' "$nth"
Storing two fields, 2nd and 3rd in just one variable name.
read -rp "Enter args: "
nth=$(awk '{\*Do some stuff with fields*\; print $2, $3}' <<< "$REPLY")
printf 'The argument was %s\n' "$nth"
If you want to split the 2nd and 3rd field in a different variable name.
read -rp "Enter args: "
nth=$(awk '{\*Do some stuff with fields*\; print $2, $3}' <<< "$REPLY")
printf 'Your 2nd argument was %s\nYour 3rd argument was %s\n' "${nth#* }" "${nth% *}"
- The
"${nth#* }"
and "${nth% *}"
can be saved with a separate variables.
One more answer to this awk
printing all the fields using $0
and read
which comes back to my first answer using read -ra
read -rp "Enter args: "
read -ra fields < <(awk '{\*Do some stuff with fields*\;print $0}' < <(printf '%s' "$REPLY"))
Print All the fields
printf '%s\n' "${fields[@]}"
- My first post/answer to this question shows how to loop throught the fields of bash arrays and how it is indexed as well.