0

I am having trouble setting my variables to the correct string in my UNIX shell script. Here is my code ($1 is a filename):

nameIndex=$(echo "$lineCount+3" |bc);
name=$(sed -n -e "$nameIndexp" -e "$nameIndexq" $1);
echo "$name";

When $lineCount is 270, the output is just a new line. That is, $name is not printed or not evaluated.

If $lineCount is 270, I want the output to be sed -n -e 273p -e 273q filename.txt which essentially prints the 273rd line of filename.txt

I appreciate your time!

Ashish
  • 1,856
  • 18
  • 30
drewyupdrew
  • 1,549
  • 1
  • 11
  • 16
  • `lineCount` is unlikely to be a floating-point value, so you can use `nameIndex=$(( lineCount + 3 ))` instead of calling the external `bc` program. – chepner Nov 19 '13 at 13:18

3 Answers3

4

$nameIndexp and $nameIndexq look like unique variable names, so you need to use ${name} syntax, i.e.

${nameIndex}p

and

${nameIndex}q

to separate the variable name from the plain text.

nameIndex=$(echo "$lineCount+3" |bc)
name=$(sed -n -e "${nameIndex}p" -e "${nameIndex}q" $1)
echo "$name"
kfsone
  • 23,617
  • 2
  • 42
  • 74
  • 3
    Its better to not use back tics. Not sure why you have changed the original parentheses one one line to back ticks and not the other. Use: `nameIndex=$(echo "$lineCount+3" |bc)` – Jotne Nov 19 '13 at 06:56
1

You can do math in bash without using bc like this:

nameIndex=$(($lineCount+3))
Jotne
  • 40,548
  • 12
  • 51
  • 55
0

try this:

nameIndex=`echo "$lineCount+3" |bc`
par=$1
name=$(sed -n -e "$nameIndexp" -e "$nameIndexq" $par)
echo "$name"