击:将行成初步意见后,源$ C ​​$ C文件 [英] Bash: Insert line into source code file after initial comments

查看:87
本文介绍了击:将行成初步意见后,源$ C ​​$ C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用bash插入一行到一个Python文件。这条线后,需要在文件的初步意见出现。

所以给出的文件:

 #!的/ usr / bin中/蟒蛇
#这只是
#为例评论哞=牛
...等...

我需要一个bash命令插入新行是这样的:

 #!的/ usr / bin中/蟒蛇
#这只是
#为例评论
新行云HERE哞=牛
...等...

我完全难倒如何做到这一点。我曾尝试过循环按行文件中的行,但只是最终被pretty可怕,严重搞乱了文件的空白。

任何建议将是伟大的!

亚当

PS。是的,这是一个有点怪异的事情,它是一个持续集成构建脚本的一部分。


修改

有关备案,code我试图为:

  insert_setup_ code(){
    安装= FALSE
    TMPFILE =/ tmp目录/ $ RANDOM    猫$ INSTALL_TO|而读-d \\ n升;做
        回声$ L>> $ TMPFILE
        如果[! $安装和放大器;&安培; ! `回声$ L| grep的^#`];然后
            回声的code线HEREGT&;> $ TMPFILE
            安装=真
        科幻
    DONE
}


解决方案

我会写:

 行=新的东西在这里
AWK -v文本=$线'/ ^#/&安培;!&安培; !p {打印文本; P = 1} 1'文件

第一个非注释行会触发块打印行:


  • / ^#/ - !行不以哈希启动

  • P ! - 变量p是不是真的

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:

line="NEW STUFF HERE"
awk -v text="$line" '!/^#/ && !p {print text; p=1} 1' file

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

这篇关于击:将行成初步意见后,源$ C ​​$ C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆