Home > Blockchain >  Add new variable to text files if a variable is found using bash
Add new variable to text files if a variable is found using bash

Time:12-03

In multiple text files, let's say a variable is present.

VariableX:
A:1
B:1
D:1

Now, if C:0 has to be added in all these text files just after B:1 (C is inserted on a new line with space aligned), how can this be done for multiple files from bash.

New text files change should look like this:

VariableX:
A:1
B:1
C:0
D:1

This can be done manually by opening each file. But there are many files, is there a way to automate or write a script in bash for this.

git grep VariableX would give all files with VariableX. Is there a way to expand this command to insert C:0.

CodePudding user response:

Given a list of files, use for to loop to insert rows.

files=$(ls | grep -E '.txt|.py|.java')
for file in ${files}
do
    sed -i '/B:1/aC:0' ${file}
    sed -i '/A:1/d' ${file}
done
  • Related