technopathe
technopathe

Reputation: 107

store awk output in variable

I ignore what is the problem with this code ?

#! /bin/bash
File1=$1
for (( j=1; j<=3; j++ ))
{
    output=$(`awk -F; 'NR=='$j'{print $3}' "${File1}"`)
    echo ${output}
}

File1 looks like this :

Char1;2;3;89
char2;9;6;66
char5;3;77;8

I want to extract on every line looped the field 3

so the result will be

3
6
7

Upvotes: 2

Views: 13305

Answers (4)

Kusalananda
Kusalananda

Reputation: 15613

If you simply want to extract a column out from a structured file like the one you have, use the cut utility.

cut will allow you to specify what the delimiter is in your data (;) and what column(s) you'd like to extract (column 3).

cut -d';' -f3 "$file1"

If you would like to loop over the result of this, use a while loop and read the values one by one:

cut -d';' -f3 "$file1" |
while read data; do
  echo "data is $data"
done

Would you want the values in a variable, do this

var=$( cut -d';' -f3 "$file1" | tr '\n' ' ' )

The tr '\n' ' ' bit replaces newlines with spaces, so you would get 3 6 77 as a string.

To get them into an array:

declare -a var=( $( cut -d';' -f3 "$file1" ) )

(the tr is not needed here)

You may then access the values as ${var[0]}, ${var[1]} etc.

Upvotes: 1

Aaron
Aaron

Reputation: 24802

Even easier, use the cut utility : cut -d';' -f3 will produce the result you're looking for, where -d specifies the delimiter to use and -f the field/column you're looking for (1-indexed).

Upvotes: 1

JNevill
JNevill

Reputation: 50034

  1. You are mixing single quotes and backticks all over the place and not escaping them
  2. You can't use bash variables in an awk script without using the -v flag
  3. awk already works in a loop so there is no reason to loop the loop...

Just:

awk -F";" '{print $3}' "${file1}"

Will do exactly what your entire script is trying to do now.

Upvotes: 1

Alexander Tolkachev
Alexander Tolkachev

Reputation: 916

It should be like this:

#! /bin/bash
File1=$1
for (( j=1; j<=3; j++ ))
{
                output=$(awk -F ';' 'NR=='$j' {print $3}' "${File1}")
                echo ${output}
}

It working well on my CentOS.

Upvotes: 5

Related Questions