简体   繁体   English

在模式后匹配单词并使用 sed 在文件中附加后缀?

[英]Match word after pattern and append a suffix in a file using sed?

I have multiple files like this one:我有多个这样的文件:

CREATE TABLE VAI_TEST
   (
      TEST VARCHAR2(4000)
   ) ;

Only the first line is relevant.只有第一行是相关的。 I need to replace VAI_TEST with VAI_TEST_TEMP.我需要用 VAI_TEST_TEMP 替换 VAI_TEST。 The result should be like this:结果应该是这样的:

CREATE TABLE VAI_TEST_TEMP
   (
      TEST VARCHAR2(4000)
   ) ;

I've found multiple regex pattern that match VAI_TEST eg我发现了多个匹配 VAI_TEST 的正则表达式模式,例如

  • (?:CREATE TABLE )([A-Za-z_]*)[\\r\\n]
  • (?:.* TABLE )(.*$)
  • CREATE TABLE (.*)\\n
  • (?:.* TABLE )(.*)\\n

Probably there are more and better patterns.可能有更多更好的模式。 My problem is to replace the content of capture group 1 with the content and the suffix.我的问题是用内容和后缀替换捕获组1的内容。

I've tried multiple sed combinations but mostly nothing happens or I get an error for a wrong regex pattern (with -r flag) or invalid reference \\1 (with -e) flag.我尝试了多种 sed 组合,但几乎没有任何反应,或者我收到错误正则表达式模式(带有 -r 标志)或无效引用 \\1(带有 -e)标志的错误。

In the end I want to use the command in a bash script.最后,我想在 bash 脚本中使用该命令。 Additionally it would be helpful if the new name could be saved in a variable to use it in further steps.此外,如果可以将新名称保存在变量中以在进一步的步骤中使用它,将会很有帮助。

What is a good way to achieve this?实现这一目标的好方法是什么?

sed '/^CREATE TABLE/s/[^ ]*$/&_TEMP/' file

  • /^CREATE TABLE/ - on lines beginning with "CREATE TABLE", /^CREATE TABLE/ - 在以“CREATE TABLE”开头的行上,
  • s/[^ ]*$/ - replace non-space characters ( [^ ] ) before the endline ( $ ) with: s/[^ ]*$/ - 将结束行 ( $ ) 之前的非空格字符 ( [^ ] ) 替换$
  • &_TEMP - & -- whatever those characters were-- suffixed with "_TEMP" &_TEMP - & - 无论这些字符是什么 - 以“_TEMP”为后缀

Consider考虑

sed -i 's/CREATE TABLE [^[:space:]]\{1,\}$/&_TEMP/' file

[^[:space:]] is for any symbol other than whitespace and \\{1,\\} repeats it one or more times. [^[:space:]]用于除空格之外的任何符号,并且\\{1,\\}重复一次或多次。 & stands for the &代表

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

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