【问题标题】:modifying text to a file将文本修改为文件
【发布时间】:2016-11-10 01:34:17
【问题描述】:

我正在尝试修改我的脚本。

create table T1
a,
b)
/
INSERT...
/
UPDATE ...   
/
create table T2
a,
b)
/

我想修改如下文件:

create table T1
a,
b) TABLESPACE TS
/
INSERT...
/
UPDATE ...   
/
create table T2
a,
b) TABLESPACE TS
/

所以我想在“create table”和“/”之间获取文本,并将“TABLESPACE TS”这个词添加到“/”这个词的上方。 有人可以帮我在 sed 命令中使用哪些选项吗?

【问题讨论】:

  • 添加了bash 标签。如果您不使用 bash,请随时回滚到以前的版本

标签: bash awk sed grep


【解决方案1】:

使用/ 作为记录分隔符。

awk -v RS=/ -v ORS=/ -v IGNORECASE=1 '
    /create table/ { print $0, "TABLESPACE TS\n";next } 
    $0 != "\n" 
    END {printf("\n")}'  inputfile > outputfile

【讨论】:

    【解决方案2】:

    输入

    create table T1
    a,
    b)
    /
    create table T2
    a,
    b)
    /
    Some Stuff
    b)
    /
    b) again
    

    脚本

    sed '/^create table/{:l1;n;/^\/$/!{s/^b)$/b) TABLESPACE TS/g;b l1}}' file
    

    输出

    create table T1
    a,
    b) TABLESPACE TS
    /
    create table T2
    a,
    b) TABLESPACE TS
    /
    Some Stuff
    b)
    /
    b) again
    

    这里发生了什么?

    • 我们在这里使用了sed 流编辑器。
    • s sed 的选项,表示替换。
    • s 格式为 s/pattern/replacement/g,其中 g 标志用于全局替换。
    • :l1 用于指定标签l1
    • n 在打印当前空间后将下一行添加到模式空间。
    • !{group} 用于否定一组命令。在我们的例子中,如果模式 / 匹配,则不要尝试 {group} 的命令。
    • b 用于无条件跳转到标签。所以b l1 跳转到标签l1
    • 现在根据这些要点阅读答案。

    注意

    SEd 本身扩展为流编辑器。更多信息请查看[ this ]

    【讨论】:

    • 还有其他文字和“/”这个词,所以替换不会起作用。必须抓住“创建表”和“/”之间的块,然后需要修改。其他文字需要保持不变。
    • @AjaySingh:我明白了。最初没有提到这一要求。我马上更新。
    • @AjaySingh :我已经更新以符合要求。
    • 为我节省了很多时间。感谢您的快速回答
    【解决方案3】:

    与 GAWK

        awk 'BEGIN{RS="\n/"} {printf "%s",$0} /create/{printf "%s"," TABLESPACE TS"} {printf "%s",RS}' file
    

    输出

    create table T1
    a,
    b) TABLESPACE TS
    /
    INSERT...
    /
    UPDATE ...
    /
    create table T2
    a,
    b) TABLESPACE TS
    /
    

     BEGIN{RS="\n/"} #set RS 
        {printf "%s",$0}  # print record
        /create/{printf "%s"," TABLESPACE TS"} #append if create is present in record
        {printf "%s",RS} # append seperator
    

    【讨论】:

    • 由于多字符 RS,您应该提到这是 gawk 特有的。此外,始终使用printf "%s", $0 而不是printf $0 - 想象一下$0 包含像%s 这样的printf 格式字符时的区别。
    猜你喜欢
    • 1970-01-01
    • 2010-09-12
    • 2014-08-16
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多