I tried to add new string using shell script when the code line have "MSG_LOG". I did add new string at the new line using this shell script,
#!/bin/bash
############Set File Name
fileName=$1
echo ">>>>Set_FileName is done"
echo ">>>>fileName is ${fileName}"
############Get Elements
lineNumArr=(`grep -n "MSG_LOG" $fileName | awk -F ':' '{print $1}'`)
echo ">>>>Getting LineNumArr is done"
for lineNum in "${lineNumArr[@]}"
do
############Replace logger
sed -i "${lineNum} a printf('MSG_Log is show');" $fileName
echo ">>>>Replace_logger is Done"
done
echo ">>>>for loop is closed"
exit
But it doesn't keep tabs on existing lines of code. For Example, I want to make my .cpp file like this,
#include<iostream>
int main(void){
bool value=true;
....
if(value){
MSG_LOG("VALUE IS TRUE");
printf('MSG_LOG is show');
}
....
But when I actuate this shell script, the result is...
#include<iostream>
int main(void){
bool value=true;
....
if(value){
MSG_LOG("VALUE IS TRUE");
printf('MSG_LOG is show');
}
....
How can I add new code while preserving the tablines?
CodePudding user response:
You should add the same amount of withespace as the previous line when adding a new line.
You want something like this
sed -E 's/^(.*)(MSG_LOG\(.*\);)(.*)$/\1\2\3\n\1printf("MSG_LOG is show");/g'
If I understood correctly.
You don't have to invoke sed
once per line as it loops over the entire file.
Also, you need double quotes in printf
.
CodePudding user response:
Using sed
, you can duplicate the original line containing MSG_LOG
and then replace the text, this will keep the tab spacing in place.
$ sed "/MSG_LOG/{p;s/[[:alpha:]].*/printf('MSG_LOG is show');/}" "$fileName"