6

I am trying to print the value of VARI in the same line followed by a comma, so that i can have a csv file of these values, but i m not able to save the value of VARI = 'cat filename | head -1 | cut -d, -f${i}'

i=0
while (( i<130)) ;
do
  if [[ $i -eq 1 ||  $i -eq 9 || $i -eq 12 || $i -eq 23 || $i -eq 25 || $i -eq 29 ]]
  then
    VARI = 'cat filename | head -1 | cut -d, -f${i}'
    echo  "$VARI ,"   
  fi
  let i=$i+1;
done

output expected is

4,abc,5,8,xyz,9

Please let me know what i am doing wrong, thanks!

6
  • I don't know how to put back quote. But In VARI the line should have back quote Commented Aug 5, 2011 at 15:45
  • @badawi -- tried it, does not work..first.sh: line 8: VARI = cat filename | head -1 | cut -d, -f${i}: command not found Commented Aug 5, 2011 at 15:48
  • @badawi: VARI = `cat filename | head -1 | cut -d, -f${i}` :) Commented Aug 5, 2011 at 15:49
  • @knittl: how did you do that? Commented Aug 5, 2011 at 15:51
  • first.sh: line 8: VARI: command not found.. am i missing something? Commented Aug 5, 2011 at 15:54

1 Answer 1

13

Use backticks (or $() which can be nested), not single quotes:

VARI=`cat filename | head -1 | cut -d, -f${i}` # or:
VARI=$(cat filename | head -1 | cut -d, -f${i})

Make sure to not have spaces between the variable name, the equal sign, and the variable value.

VAR = x # executes program "VAR" with 2 parameters: "=" and "x"
VAR =x  # executes program "VAR" with a single parameter: "=x"
VAR= x  # executes program "x" with environment variable "VAR" set to an empty value
VAR=x   # assigns value "x" to shell variable "VAR"

Resources: 2.10.2 Shell Grammar Rules of the POSIX.1-2017 specification.

Sign up to request clarification or add additional context in comments.

2 Comments

first.sh: line 8: VARI: command not found.. am i missing something?
Awesome.. thanks! .. works!.. such silly mistake!.. did not realise the importance of space ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.