简体   繁体   English

如何使用 sed 替换包含整数的行

[英]How to replace lines that contains integers by using sed

I have a file that contains two fields.我有一个包含两个字段的文件。 The first field may or may not contain an Integer.第一个字段可能包含也可能不包含整数。 If it contains an integer and a dot follows the integer I would like to manipulate part of second field.如果它包含一个整数并且一个点跟在整数后面,我想操纵第二个字段的一部分。 So As an example:所以作为一个例子:

301.    301+Num+Ord          # Change this one 301+Num+Card
100.    100+Num+Ord          # Change this one 100+Num+Card 
3'üncü  3+Num+Ord            # DONOT CHANGE THIS ONE
48.7    48.7+Num+Real        # DONOT CHANGE THIS ONE EITHER . is not at the end
24      24+Num+Card          # DONOT CHANGE THIS ONE No dot
4.      4+Num+Ord          #  Change this one 4+Num+Card
.        .+Punct              # DONOT CHANGE THIS ONE 

I couldn't make it since I have very limited knowledge in regex.我无法做到,因为我对正则表达式的了解非常有限。 I would be very appreciate if you can help me.如果您能帮助我,我将不胜感激。 thanks谢谢

Could you please try following awk command and let me know if this helps you.您能否尝试遵循 awk 命令并告诉我这是否对您有帮助。 Since you haven't told us which is the next text which you want on place of 2nd column in case it needs to be changed I am simply taking a test string.由于您没有告诉我们哪个是您想要在第 2 列处替换的下一个文本,以防它需要更改,因此我只是采用了一个测试字符串。

awk '($1 ~ /[0-9]+\.$/){sub("Ord","Card",$2)} 1' OFS="\t" Input_file

Explanation: awk has by default delimiter as space so $1 represents column 1 here.说明: awk默认将分隔符作为空格,所以$1 1 在这里代表第 1 列。 So I am checking here by doing $1 ~ /[0-9]+\\./$ here if a 1st column is having digits in it followed by a DOT at last of column( \\. means I am using escape sequence to remove DOT's special meaning here), if yes then I am substitute ord with card in 2nd field by using sub (substitute) utility of awk here.所以我在这里检查$1 ~ /[0-9]+\\./$如果第一列中有数字,然后在列的最后一个 DOT( \\.表示我正在使用转义序列来删除 DOT这里的特殊含义),如果是,那么我在这里使用awk sub (替代)实用程序在第二个字段中用card替代ord Then 1 means I am making condition TRUE here and not mentioning and action here so by default action print will happen.然后1表示我在此处设置条件为 TRUE 而未在此处提及和操作,因此默认情况下将发生操作打印。

OP 要求 sed 所以

sed -E '/^[0-9]+\.[[:space:]]/!b;s/(^.*[[:space:]]+)([^[:space:]]*$)/\1Change this one/' infile

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

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