ArmadilloChubbz65
ArmadilloChubbz65

Reputation: 303

How to write the quantity of lines in a file to a line in a seperate file using bash

I want to count the number of lines in one file, and then overwrite a number in a second file with the number of lines. E.g.

file1.txt

Apples
Oranges
Bananas

file2.txt

num_lines_in_file_1 = 100

So I need to replace 100 with 3

file2.txt

num_lines_in_file_1 = 3

I seen that the wc -l file1.txt command can tell me the number of lines. And I know I can replace a line using sed e.g.

sed -i "s/num_lines_in_file_1 = 100/num_lines_in_file_1 = 3/" file2.txt

However I don't understand how you would pipe | the wc command into sed? Would it happen inside the regular expression?

Upvotes: 0

Views: 70

Answers (1)

choroba
choroba

Reputation: 241868

Use command substitution:

sed -i "s/num_lines_in_file_1 = 100/num_lines_in_file_1 = $(wc -l < file1.txt)/" file2.txt

You also don't need to repeat the whole phrase, sed can remember it for you:

sed -i "s/\(num_lines_in_file_1 = \)100/\1$(wc -l < file1.txt)/" file2.txt

Upvotes: 2

Related Questions