在特定行中匹配和替换sed的数字

时间:2013-07-30 23:29:26

标签: bash replace sed awk pattern-matching

使用Ubuntu 12.04和vim 2.22.0,在vim编辑器中我将使用:

:9;13;17;21s/\d\+/1/

匹配^ M之前的数字(有时只是没有任何尾巴的数字)并将它们更改为1.此模式仅出现在第9,13,17和21行的开头。即:

vi _ccc_info_datasets:

...
=====
2
../../automotive_susan_data/2.pgm output_large.corners.pgm -c > ftmp_out
691^M  // ---------> change to 1^M
=====
...

据我了解,同样不能像sed一样:

find . type f  -name "_ccc_info_datasets" -exec sed -i '9;13;17;21s/\d\+/1/' {} \;

用于更改bash中的多个文件。我试过了:

find . type f  -name "_ccc_info_datasets" -exec sed -i '9;13;17;21s/[0-9]{1;\}/1/' {} \;

但它执行时没有错误但没有结果。任何帮助表示赞赏;)

1 个答案:

答案 0 :(得分:0)

你不能像那样使用sed。您需要使用-e开关使用多个sed替换:

sed -i.bak -e '9s/[0-9][0-9]*\('$'\r''\)/1\1/' -e '13s/[0-9][0-9]*\('$'\r''\)/1\1/' \
    -e '17s/[0-9][0-9]*\('$'\r''\)/1\1/' -e '21s/[0-9][0-9]*\('$'\r''\)/1\1/' file

更新:虽然awk不支持内联编辑,但我相信使用awk会更加干净。请考虑下面的awk命令:

awk 'NR ~ /^9|13|17|21$/{sub(/[0-9]+\r$/, "1\r")}1' file > _temp && mv _temp file