I need to use bash to insert a line into a python file. This line needs to appear after any initial comments in the the file.
So given the file:
#!/usr/bin/python
# This is just
# an example comment
moo = "cow"
... etc ...
I need a bash command to insert a new line like this:
#!/usr/bin/python
# This is just
# an example comment
NEW LINE GOES HERE
moo = "cow"
... etc ...
I am entirely stumped on how to do this. I have tried looping over the file line by line, but that just ends up being pretty horrific and severely messing up the file’s whitespace.
Any suggestions would be great!
Adam
PS. Yes, this is a bit of a weird thing to do, it is for part of a continuous integration build script.
Edit
For the record, the code I was trying was:
insert_setup_code() {
installed=false
tmpfile="/tmp/$RANDOM"
cat "$INSTALL_TO" | while read -d \n l; do
echo "$l" >> $tmpfile
if [[ ! $installed && ! `echo "$l" | grep "^#"` ]]; then
echo "LINE OF CODE HERE" >> $tmpfile
installed=true
fi
done
}
I would write:
The first non-comment line will trigger the block to print the line:
!/^#/— line does not start with a hash!p— variable p is not true