简体   繁体   中英

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

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.

  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.

Even easier, use the cut utility : cut -d';' -f3 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM