TransWikia.com

Extract value of column from a line (variable)

Stack Overflow Asked by user4516211 on December 4, 2020

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.

4 Answers

Using plain POSIX features:

#!/usr/bin/env sh

line='abc:123:def:345'

IFS=:
# Split line on IFS into arguments
set -- $line

printf %s\n "$2"

Alternate method:

#!/usr/bin/env sh

line='abc:123:def:345'

# Strip out first column
a="${line#*:}"

# Strip out remaining columns except 1st
b="${a%%:*}"

printf %s\n "$b"

Answered by Léa Gris on December 4, 2020

way in bash using expr

Line2=$(expr $line : "[^:]*:([^:]*)")

or if the fields are always 3 characters

Line2=${line:4:3}

Answered by user4453924 on December 4, 2020

You can use awk to get second field:

line="abc:123:def:345"

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

Answered by Jotne on December 4, 2020

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

Answered by glenn jackman on December 4, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP