I want to run a CFD simulation which is split into 2 steps. After the end of 1st step, I need to change a text file (related to boundary conditions - CFD terminology) and re-run the case further that is step 2.
Until now, I was doing this manually and lost lot of time to run the simulations overnight and over the weekends.
So, is it possible to edit a text file using a bash script?
Example: My file structure:
TestRun
Folder1
-- TextFile1
TestRun (main folder) consists of a sub-folder (Folder1) and Folder1 has a text file to be edited (TextFile1) by a bash script.
Content of TextFile1 (for example):
internalField nonuniform List<scalar>
7
(
0
1
2
3
4
5
6
);
boundaryField
{
left
{
type fixedValue;
value uniform 1;
}
}
Now, the bash file shall change the file as:
internalField nonuniform List<scalar>
7
(
0
1
2
3
4
5
6
);
boundaryField
{
left
{
type groovyBC;
valueExpression "-pc";
variables "pc@left=pc;";
value uniform 0;
}
}
Please note, that the number of lines to be edited is more than 1 and I do not know the line number in specific. I did come across few posts editing one specific line number using sed.
In my case, I must find the word "left" (as in vim: /left) and replace the lines inbetween '{ }' following the searched word.
Taking for granted the word "left" will only appear once in the file, you can use this script to perform the edit you want:
#!/bin/bash
#
insideleft='false'
while read line
do
# using grep -c to make sure it matches even if there are spaces
if [ $(echo $line | grep -c left) -eq 1 ]
then
insideleft='true'
cat <<HEREDOC
left
{
type groovyBC;
valueExpression "-pc";
variables "pc@left=pc;";
value uniform 0;
}
HEREDOC
else
if [ $insideleft == 'false' ]
then
echo $line
else
if [ $(echo $line | grep -c '}') -eq 1 ]
then
insideleft='false'
fi
fi
fi
done <data
Basically, once the line "left" is found, output the new text, and loop over the input file lines until the }, closing the left section is found. I tried it with your input and output sample, it works fine.
Note: in the last line, "data" is the filename you want to modify.