Extract value of column from a line (variable)

10,307

Solution 1

You can use awk to get second field:

line="abc:123:def:345"

awk -F: '{print $2}' <<< "$line"
123

Solution 2

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
Share:
10,307
user4516211
Author by

user4516211

Updated on June 27, 2022

Comments

  • user4516211
    user4516211 over 1 year

    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.