How to extract values from a command with multi-line output?
Bo Berglund
bo.berglund at gmail.com
Mon Apr 4 21:02:37 UTC 2022
On Mon, 4 Apr 2022 14:59:37 -0400, Peter Teuben <teuben at gmail.com> wrote:
>Hi Bo,
>
> I have this "problem" a lot, and you can do this with awk, but the
>scripts are so "awkward" looking, and I wrote a little C program for
>this (which really you don't want to use), but I call this one as follows:
>
>
>fdisk -lu filename.img | tail -n 2 | txtpar -p0=1,2 p1=1,4 p2=2,2
>
>
>but in awk I might write a 123.awk script: (chmod +x 123.awk)
>
>#! /usr/bin/awk -f
>#
>
>{
> if (NR==1) { a=$2; b=$4;}
> if (NR==2) { c=$2; }
>}
>
>END {
> print a,b,c;
>}
>
>then you cn
>
>fdisk -lu filename.img | tail -n 2 | ./123.awk
>
>
>but in unix there are probably 10 different solutions to this.
>
I have a script which is used to log Internet access speed on a remote location.
It uses Ookla Speedtest CLI program in a script where the rather large output is
stripped down to only the parts I need using this:
CMD="speedtest --format=tsv"
RESULT=$($CMD)
IFS=$'\t' read -ra data_array <<< "$RESULT"
#Extract values from array
latency=${data_array[2]}
#Convert decimal separator from . to ,
latency=$(sed 's/\./,/g' <<< "$latency")
download=$(eval "echo \"scale=1 ; ${data_array[5]} * 8 / 1000000\" | bc")
download=$(sed 's/\./,/g' <<< "$download")
upload=$(eval "echo \"scale=1 ; ${data_array[6]} * 8 / 1000000\" | bc")
upload=$(sed 's/\./,/g' <<< "$upload")
resultid=${data_array[9]}
RESULT="${latency}\t${download}\t${upload}\t${resultid}"
eval "echo -e \"${RESULT}\" >> $LOGFILE"
This works fine to produce a sensible log file. But it handles a single line of
result data...
So I tried to use a similar technique as follows, where I want to stuff complete
lines into the array:
CMD="fdisk -lu $IMGFILE | tail -n 2"
DSKDATA=$(eval "$CMD")
IFS=$'\n' read -ra data_array <<< "$DSKDATA"
echo "Result in array: "
echo "${data_array[0]}"
echo "${data_array[1]}"
echo " "
echo "Full result:"
echo -e -n "$DSKDATA\n"
The output looks like this:
Result in array:
filename.img1 8192 532479 524288 256M c W95 FAT32 (LBA)
Full result:
filename.img1 8192 532479 524288 256M c W95 FAT32 (LBA)
filename.img2 532480 3923967 3391488 1.6G 83 Linux
So the lines clearly do not get split into a 2-element array, instead line 2 is
lost in the array.
What am I doing wrong here?
--
Bo Berglund
Developer in Sweden
More information about the ubuntu-users
mailing list