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
}
you could add the stub, your new line, and remaining stuff as variables in the bash script, i.e.
and pipe them into your new script
i gues the
YOUR_LINE
variable is dynamic, but if theHEADER
andREST
are static that should work, if these are dynamic as well, then you could usehead
andtail
in combination withwc -l
to calculate what lines should be includedI 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 trueUsing
ed
there is no need for a tmp file.The following code assumes that there are only empty lines or lines beginning with a
#
char before the first non-empty line that does not begin with a#
char.If you insist that the line gets inserted exactly after the initial comments, you can do that as well.
there you go
my
addline
script. addnewline
after any initial comments in thefilein
and write tofileout
Use as:
adjust to your needs :)
example usage to itself:
Updated faster version:
using
wc -l
andsed
to write the rest of the file instead of looping through each lineworks as before/above
FYI, your bash version would go like this
But of course additional setps should be taken if you want to preserve metadata on the
$install_to
fileLocate the first empty line
Use that line number and change it to some other string,
-i
to edit files in place (use with care!)A different approach is to grep for the first line that do not contain a
#
, then the above becomes:To use a shell variable in a sed-script, use this aproach, where
"
allow variables to be expanded