在pattern包含\ n - linux命令行时查找并替换

时间:2013-07-22 13:00:24

标签: linux text replace sed awk

我有一个文件,我想替换一个以行尾\n终止的模式...我在网上搜索了一种方法来执行此操作,但它们都不起作用......我可以将行尾替换为其他内容,但不能替换包含行尾的模式..

这是一个例子 文本文件包含:

22.0,26235,-48.4,-999,-999,-999,100,22,669.0,-999,669.0
20.0,26860,-47.5,-999,-999,-999,100,21,690.0,-999,690.0
19.3,27096,-47.1,-999,-999,-999,100,21,698.3,-999,698.3
19.0,-999,-999,-999,-999,-999,100,21,-999,-999,

最后一行中缺少一个值(可以在任何其他行中),我想找到\n并替换为-999

所以文字就像这样:

22.0,26235,-48.4,-999,-999,-999,100,22,669.0,-999,669.0
20.0,26860,-47.5,-999,-999,-999,100,21,690.0,-999,690.0
19.3,27096,-47.1,-999,-999,-999,100,21,698.3,-999,698.3
19.0,-999,-999,-999,-999,-999,100,21,-999,-999,-999

任何想法????

7 个答案:

答案 0 :(得分:2)

你可以说:

sed 's/,[^0-9]*$/,-999/' filename

答案 1 :(得分:2)

使用awk

awk 'BEGIN{FS=OFS=","}{if($11==""){$11="-999"};print}' your.file

如果该列为空,该命令会将第11列设置为-999


用户sudo_O建议上面的脚本版本采用相同的逻辑,但看起来更清晰:

awk '$11==""{$11=-999}1' FS=, OFS=, your.file 

答案 2 :(得分:1)

这个sed应该有效:

sed -i.bak 's/, *$/&999/' file

答案 3 :(得分:0)

可能会将,\n替换为,-999\n

sed 's/\,\n&/\,-999\n&/g' file_name

答案 4 :(得分:0)

也许你可以使用awk分隔符变量,如下所示:

#!/usr/bin/awk -f
BEGIN {
    FS=",";
    OFS=",";
}
{
    if ( $11 == "") {
        print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,"-999"
    } else {
        print $0
    }
}

答案 5 :(得分:0)

$ awk '{print $0 (/,$/?-999:"")}' file
22.0,26235,-48.4,-999,-999,-999,100,22,669.0,-999,669.0
20.0,26860,-47.5,-999,-999,-999,100,21,690.0,-999,690.0
19.3,27096,-47.1,-999,-999,-999,100,21,698.3,-999,698.3
19.0,-999,-999,-999,-999,-999,100,21,-999,-999,-999

或者如果你喜欢高尔夫:

$ awk '/,$/{$0=$0"-999"}1' file
22.0,26235,-48.4,-999,-999,-999,100,22,669.0,-999,669.0
20.0,26860,-47.5,-999,-999,-999,100,21,690.0,-999,690.0
19.3,27096,-47.1,-999,-999,-999,100,21,698.3,-999,698.3
19.0,-999,-999,-999,-999,-999,100,21,-999,-999,-999

就个人而言,我只是使用其中一个发布的简单sed解决方案,例如: @ anubhava的

答案 6 :(得分:0)

这可能适合你(GNU sed):

sed -r 's/[^,]+/&/11;t;s/$/-999/' file

如果没有第11个字段追加-999