Okay, so I have a variable ($line) that is defined in the bash/shell script as
$line = "abc:123:def:345"
need to get this column2 = "123"
How do I extract the value of the 2nd column i.e. "123" and name it as a different variable which can be summed later on? I know you have to separate it based on the delimiter ':' but I don't know how to transfer to different variable whilst taking input from $line variable. I only ask this because for some weird reason my code reads the first line of text file BUT doesn't perform the awk on just the first line only so hence the sum is wrong.
FILE=$1
while read line
do
awk -F: '{summation += $3;}END{print summation;}'
done < $FILE
-code via shell script
Thanks.
You can use awk
to get second field:
line="abc:123:def:345"
awk -F: '{print $2}' <<< "$line"
123
To assign a variable in the shell, no $
on the left-hand side, no spaces around the =
, and <
and >
are not valid quote characters
line="abc:123:def:345"
In bash, you would do this:
IFS=: read -ra fields <<< "$line"
IFS
to a colon$line
variable as input to the read
command (a here-string)fields
array.Bash arrays are indexed starting from zero, so to extract the 2nd field:
echo "${fields[1]}" # => 123
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With