2

I would like to extract all the values contained in $line and put them in variables var1, var2,... varn. I did use this previously to extract the vars from file (in.txt)

var1=$(awk  '{print  $1}' < in.txt)
var2=$(awk  '{print  $2}' < in.txt)
....
varn=$(awk  '{print  $n}' < in.txt)

How should I change my awk call so as to use $line instead of in.txt? I tried these for example

echo $line | var2=$(awk '{print  $2}')

or

var2=$(echo $line | awk '{print  $2}')

but without success...

========== DETAIL==============

----- calling file:

 .....
    name=Matrix
    line=$(sed  -n '/^\[T\]/ {n;p}' in.txt)
    echo 'line: ' $line
    L1=$(./procline_matrix_vars.sh $line 30 $name)
    echo 'L1: ' $L1

------- rocline_matrix_vars.sh:

#!/bin/bash

line=$1
choice=$2

var1=$(echo $line | awk '{print $1}')
var2=$(echo $line | awk '{print $2}')
var3=$(echo $line | awk '{print $3}')
var4=$(echo $line | awk '{print $4}')


if [ $choice == 30 ]; then
    L1=$(printf '\n\n\n%s = [ %s %s %s %s \n' "$3" "$var1" "$var2" "$var3" "$var4") 
fi

echo  "${L1%.}"
6
  • var2=$(echo $line | awk '{print $2}') should work, is it not giving you any values when you do echo "var2"? Commented Apr 9, 2018 at 14:21
  • It works only for the 1st value in in string. Commented Apr 9, 2018 at 14:24
  • see also mywiki.wooledge.org/BashFAQ/001 Commented Apr 9, 2018 at 14:26
  • @Sundeep I am clearly stating "awk". Commented Apr 9, 2018 at 14:35
  • 1
    not sure why you need awk.. also, variable quoting may be an issue.. could you change $line to "$line" in calling file and just to make it robust, double quote other places and other variables too... you can also use shellcheck.net to catch such issues Commented Apr 9, 2018 at 15:08

1 Answer 1

1

a possible way:

line="aaa bbb ccc"

var=( $line )

echo "${var[1]}"
echo "my array has ${#var[@]} elements"

output

bbb
my array has 3 elements

maybe shortcut

var=( $( awk '{print $1, $2, $10}' file ) )
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.