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.

while read line
 awk -F: '{summation += $3;}END{print summation;}'
done < $FILE

-code via shell script


4 Answers

Using plain POSIX features:

#!/usr/bin/env sh


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

printf %s\n "$2"

Alternate method:

#!/usr/bin/env sh


# Strip out first column

# Strip out remaining columns except 1st

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


Answered by user4453924 on December 4, 2020

You can use awk to get second field:


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

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


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!

Related Questions

How to insert multiple images in the Django blog app?

1  Asked on November 29, 2021 by waw-waw


Filter out Certain Words and Match only EXACT Words

1  Asked on November 27, 2021 by askmeaquestion1234


soup.find returning “none” only sometimes?

2  Asked on November 27, 2021 by c120


Raise float into the power – print formula

1  Asked on November 27, 2021 by markl


Conditional Window Functions

1  Asked on November 27, 2021 by caerus


unable to load font awesome icons in html

1  Asked on November 27, 2021 by vasilis-skentos


Why the method is returning padEnd as undefined?

1  Asked on November 27, 2021 by dev101


React js .bind(this) in hooks

1  Asked on November 27, 2021 by soukaina-benchekroun


How to get a specific name from another array by its id?

1  Asked on November 27, 2021 by ahmed-eid


Insertion Sort on a String Array

1  Asked on November 27, 2021 by 101001


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir