0

What I need to do (in Bash) is a replacement of a specific characted of the second line in a text file with the number of lines in this file. So, this does the job of counting the lines:

cat test.csv | wc -l

The following command does the job of changing the ;0; encountered in the file to be modified with the number I got from the above command (in this case 33)

sed -i '2s/;0;/;33;/' test.csv

But now I am trying to join the two above so that they work as a single command (I need it in my application). I've tried in many ways shown below, but with no success.

sed '2s/;0;/`cat test.csv | wc -l`/' test.csv
cat test.csv | wc -l | sed '2s/;0;//' test.csv
sed '2s/;0;/`${cat test.csv | wc -l}`/' test.csv
sed -e '2s/;0;/echo `${cat test.csv | wc -l}`/;e' test.csv
sed -e '2s/;0;/${echo `cat test.csv | wc -l`}/' test.csv
$rn=`cat test.csv | wc -l`; sed '2s/;0;/${rn}/' test.csv

Could anyone help me solve this out?

AdminBee
  • 22,803
WojtusJ
  • 103

1 Answers1

4

In all of your commands, you use single quotes around the sed expression. The shell will not do expansions inside single quotes.

Instead (temporarily breaking out of the single quoted expression for a double quoted command substitution),

sed '2s/;0;/;'"$( wc -l <test.csv )"';/' test.csv

or (using double quotes for the whole expression),

sed "2s/;0;/;$( wc -l <test.csv );/" test.csv

or (using a variable, and then double quotes as above),

lines=$( wc -l <test.csv ); sed "2s/;0;/;$lines;/" test.csv

(don't use -i until you know it works!)

Related:

Kusalananda
  • 333,661