简体   繁体   English

sed替换文件字符串组

[英]sed replace group of files string

I am trying to replace a string in multiple lines. 我试图在多行中替换一个字符串。 It is late and I'm getting restless, maybe someone would prefer to give it a shot for some SO points. 现在已经很晚了,我会变得焦躁不安,也许有人会更喜欢为一些SO分数。 The string I'm replacing is 'STORED AS TEXTFILE' from the SQL below... 我正在替换的字符串是'STORED as TEXTFILE',来自下面的SQL ...

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

And to make it look like... 并使它看起来像......

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

So my expression is 所以我的表达是

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

Which works inside the file (with vim) but I can't get it to work with one command on all of the files in the directory. 哪个在文件内部工作(使用vim)但是我不能让它在目录中的所有文件上使用一个命令。 I've tried so far... 到目前为止我已经尝试过了......

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

... and I also tried the above statement with all the spaces escaped. ...我还尝试了上述语句,所有空格都被转义了。 Please help! 请帮忙!

gawk in-place editing approach - available since GNU awk 4.1.0: 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 - in-place editing of each input file -i inplace - 每个输入文件的就地编辑

sed processes file line by line following link gives a solution for multiline processing https://unix.stackexchange.com/questions/26284/how-can-i-use-sed-to-replace-a-multi-line-string sed进程文件逐行跟随链接为多行处理提供解决方案https://unix.stackexchange.com/questions/26284/how-can-i-use-sed-to-replace-a-multi-line-string

otherwise in perl the default input line separator $/ can be changed or undefined (read whole file): 否则在perl中默认输入行分隔符$/可以更改或未定义(读取整个文件):

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

After reading comments on accepted answer of link, GNU sed has the -z option which does quite the same uses NUL character as line delimiter ( $\\="\\0" ), whereas undef $/ uses no delimiter. 在阅读关于链接的接受答案的评论之后,GNU sed具有-z选项,其使用NUL字符作为行分隔符( $\\="\\0" ),而undef $/使用分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM