Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract value of column from a line (variable)

Tags:

bash

shell

unix

awk

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.

like image 867
user4516211 Avatar asked Dec 25 '22 21:12

user4516211


2 Answers

You can use awk to get second field:

line="abc:123:def:345"

awk -F: '{print $2}' <<< "$line"
123
like image 199
Jotne Avatar answered Dec 31 '22 13:12

Jotne


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"
  • temporarily set IFS to a colon
  • use the $line variable as input to the read command (a here-string)
  • and read the values into the fields array.

Bash arrays are indexed starting from zero, so to extract the 2nd field:

echo "${fields[1]}"   # => 123
like image 45
glenn jackman Avatar answered Dec 31 '22 14:12

glenn jackman