【问题标题】:sed replace group of files stringsed 替换文件组字符串
【发布时间】:2017-11-14 19:24:30
【问题描述】:

我正在尝试替换多行中的字符串。已经很晚了,我变得焦躁不安,也许有人更愿意为一些 SO 点试一试。我要替换的字符串是来自下面 SQL 的“STORED AS TEXTFILE”...

PARTITIONED BY(load string, date string, source_file string)
STORED AS TEXTFILE
LOCATION '${staging_directory}/${tablename}';

让它看起来像......

PARTITIONED BY(load string, date string, source_file string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE
LOCATION '${staging_directory}/${tablename}';

所以我的表达是

:%s/)\nSTORED AS TEXTFILE\nLOCATION '/)\rROW FORMAT DELIMITED \rFIELDS TERMINATED BY ',' \rSTORED AS TEXTFILE \rLOCATION '/g

在文件中工作(使用 vim),但我无法使用一个命令处理目录中的所有文件。到目前为止我已经尝试过......

sed -i "s/)\nSTORED AS TEXTFILE\nLOCATION '/)\rROW FORMAT DELIMITED \rFIELDS TERMINATED BY ',' \rSTORED AS TEXTFILE \rLOCATION '/g"

...我还尝试了上述语句,所有空格都已转义。请帮忙!

【问题讨论】:

    标签: regex linux bash sed spaces


    【解决方案1】:

    gawk 就地编辑方法 - 自 GNU awk 4.1.0 起可用:

    gawk -i inplace '$0~/STORED AS TEXTFILE/{ $0="ROW FORMAT DELIMITED" ORS "FIELDS TERMINATED BY \047,\047" ORS $0 }1' file*
    
    • -i inplace - 就地编辑每个输入文件

    【讨论】:

    • 什么使用信息
    • 用法:gawk [POSIX or GNU style options] -f progfile [--] file ... 用法:gawk [POSIX or GNU style options] [--] 'program' file ... POSIX 选项:GNU 长选项:-f progfile --file=progfile -F fs --field-separator=fs -v var=val --assign=var=val
    • 你的操作系统是什么?
    • 它是 CentOS 6.8
    • @Mike,明白了。我应该提到自 GNU awk 4.1.0 以来可用的就地扩展,在答案中添加了注释。 rpmfind.net/linux/rpm2html/search.php?query=gawk
    【解决方案2】:

    sed 逐行处理文件下面的链接给出了多行处理的解决方案https://unix.stackexchange.com/questions/26284/how-can-i-use-sed-to-replace-a-multi-line-string

    否则在 perl 中默认输入行分隔符 $/ 可以更改或未定义(读取整个文件):

    perl -i.BAK -pe 'BEGIN{undef$/}s/.../.../g' file
    

    在阅读 cmets 接受的链接答案后,GNU sed 具有 -z 选项,它使用 NUL 字符作为行分隔符 ($\="\0"),而 undef $/ 不使用分隔符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-13
      • 2018-05-07
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多