简体   繁体   English

如何用sed文件中的某些模式替换单词?

[英]How to replace the words with certain pattern in a file with sed?

I know how to replace a word with sed. 我知道如何用sed代替单词。 Using 运用

sed -i 's/[old_text]\b/[new_text]/g'

could replace old_text with new_text. 可以用new_text替换old_text。

What I want to do is to replace nchar(10) or nchar (10) or nchar ( 10)... with char(10) in a DB schema. 我想做的是在数据库架构中用char(10)替换nchar(10)或nchar(10)或nchar(10)...。

CREATE TABLE Human
(
    ID int,
    Name nchar(10)  --> should be replace with char(10)
);

The format is quite hard to be determined. 格式很难确定。

I don't know how to set the sed regular expression to archive this. 我不知道如何设置sed正则表达式来对此进行存档。

You can make spaces optional everywhere: 您可以在任何地方使空格为可选:

sed -i.bak 's/\<nchar *( *\([0-9]*\) *)/char(\1)/g' file.sql
  • \\< is used for word boundary. \\<用于单词边界。

Or rather you can open the file in vi and use following in vi cmd mode 或者,您可以在vi中打开文件并在vi cmd模式下使用以下命令

%s/nchar/char/g

This replaces in entire file at once 一次替换整个文件

All occurrences of nchar will be replaced in one go. 一次性替换所有出现的nchar。

And to check before replacing all 并在更换所有之前进行检查

%s/nchar/char/gc

y for yes y是

n for not replacing n表示不更换

a for replacing rest all 用于替换所有休息

Using sed and extended regex -r (for clarity). 使用sed和扩展的regex -r (为清楚起见)。 Also -i means "inplace" so no need to create a different output file 另外-i表示“就地”,因此无需创建其他输出文件

sed -i sqlfile -r -e "s/nchar\s*\(\s*([0-9]+)\s*\)/char(\1)/g"

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

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