简体   繁体   English

如果部分行与sed匹配,则用数字替换行

[英]Replace a line with a number if part of it is matches using sed

I know this is a very simple question and been discussed many times, but I can't understand where I am doing wrong in my command. 我知道这是一个非常简单的问题,已经讨论了很多次,但是我不明白我的命令在哪里做错了。

I would like to replace the lines which starts with "It" as 99999. Each row starts with several blank spaces. 我想将以“ It”开头的行替换为99999。每行以几个空格开头。

infile.txt
     3
     2
     3
     4
  It is not a number = /home/kayan/data
     3
     5
  It is not a number = /home/kayan/data
     4
     5

I used 我用了

sed -i 's/^I/99999/g' infile.txt

But it is not working. 但这是行不通的。

Due to starting space, add it to pattern search 由于起始空间,请将其添加到模式搜索中

sed -i 's/^[[:blank:]]*I.*/99999/' infile.txt

using the change function 使用更改功能

sed -i '/^[[:blank:]]*I/ c\
9999' infile.txt

keeping starting space 保持起始空间

sed -i 's/^\([[:blank:]]*\)I.*/\199999/' infile.txt

No need of the g , there is only 1 change per line possible 不需要g ,每行可能只有1次更改

What you are replacing there is just the ^I part, ie the first letter. 您要替换的只是^I部分,即第一个字母。 Use ^I.* instead to match the whole remaining line and it also gets replaced. 请改用^I.*来匹配剩余的整个行,并且它也会被替换。

试试看:

sed -i 's/^\s*It.*/9999/'

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

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