string sed 替换第一行中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12526154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sed replace string in a first line
提问by irek
How can I replace a string but only in the first line of the file using the program "sed"?
如何使用程序“sed”替换文件的第一行中的字符串?
The commands s/test/blah/1
and 1s/test/blah/
don't seem to work. Is there another way?
命令s/test/blah/1
和1s/test/blah/
似乎不起作用。还有其他方法吗?
回答by potong
This might work for you (GNU sed):
这可能对你有用(GNU sed):
sed -i '1!b;s/test/blah/' file
will only substitute the first test
for blah
on the first line only.
只会替换第一个test
用于blah
仅在第一线。
Or if you just want to changethe first line:
或者,如果您只想更改第一行:
sed -i '1c\replacement' file
回答by Chris Seymour
This will do it:
这将做到:
sed -i '1s/^.*$/Newline/' textfile.txt
Failing that just make sure the match is unique to line one only:
如果失败,请确保匹配仅对第一行是唯一的:
sed -i 's/this is line one and its unique/Changed line one to this string/' filename.txt
The -i
option writes the change to the file instead of just displaying the output to stdout.
该-i
选项将更改写入文件,而不仅仅是将输出显示到标准输出。
EDIT:
编辑:
To replace the whole line by matching the common string would be:
通过匹配公共字符串来替换整行将是:
sed -i 's/^.*COMMONSTRING$/Newline/'
Where ^
matches the start of the line, $
matches the end of the line and .*
matches everything upto COMMONSTRING
Where^
匹配行的开头,$
匹配行的结尾并.*
匹配所有内容COMMONSTRING
回答by Hymantrade
this replaces all matches, not just the first match, only in the first line of course:
这将替换所有匹配项,而不仅仅是第一个匹配项,当然仅在第一行中:
sed -i '1s/test/blah/g' file
the /g did the trickto replace more than one matches, if any exists.
/g可以替换多个匹配项(如果存在)。