0

I want to use grep to count the number of W occurrences in the file.txt, save it as the variable WATER_NUMBER. Then append that number to the end of file.txt.

Following here,

I tried

#!/bin/bash -l
WATER_NUMBER="$(grep -c W file.txt)"
sed -i -e '$a\"${WATER_NUMBER}"' file.txt

but I got "${WATER_NUMBER}" printed out, instead of the number. Can I ask how to modify it?

lanselibai
  • 1,203
  • 2
  • 19
  • 35

2 Answers2

1

The command

sed -i '$a\"${WATER_NUMBER}"' file.txt

will simply add the line "${WATER_NUMBER}" at the end of the file. You could try

sed -i "$ a\$WATER_NUMBER" file.txt

but this will still add the line $WATER_NUMBER. The problem is that the variable WATER_NUMBER is not expanded in the sed script. In order to pass its value to sed, place it outside the quoting, like this

sed -i '$ a\'$WATER_NUMBER file.txt

Edit: I actually wrote my answer yesterday without really thinking about the reason as to why the variable is not expanded. This morning I wondered why this is the case even though the variable is in double quotes as opposed to single quotes. The reason is actually just the coincidence that the \ from the append command is in front of the $ from the variable, thus escaping it. To prevent this, you need to escape the \. On the other hand, a backslash is actually not needed to separate the a from the line you want to add, hence

sed -i "$ a $WATER_NUMBER" file.txt

will do the job.

Stefan Hamcke
  • 281
  • 4
  • 13
1

How to save a number to a variable?

WATER_NUMBER=42

How to append the variable content to a file?

echo $WATER_NUMBER >> file.txt
jschnasse
  • 8,526
  • 6
  • 32
  • 72