有什么方法可以获取匹配的图案线的行号? [英] Are there any ways to obtain the line number of the matched pattern line?
问题描述
例如,一个文本文件具有:
For example , A text file has:
dfsdfsd
f
dsf
dsf
dsf
dsf
sdafadfdasfdsfd
sf
sdfasdfdasfdsfsdf
sd
fsdfdsaf
然后,我想找到一种方法来获取sf的行号并在科幻小说之前插入一段
Then , i would like to find a way to obtain the line number of sf and insert a paragraph before sf
在bash编程中有什么方法可以实现吗?
Are there any ways to doing it in bash programming ???thanks
推荐答案
如果要查找行号,可以使用 grep -n
.
If you want to find out the line number, you could use grep -n
.
如果只想在前一行插入一行,则可以使用 sed
像这样:
If you just want to insert a line on the preceding line, you could use sed
like this:
sed "s/sd/paragraph\nsd/" file
这将在"sd"行上方插入文本"paragraph".
This will insert the text "paragraph" above the line with "sd".
仅在第一个比赛中执行此操作:
To only do this for the first match:
sed "0,/sd/ { s/sd/paragraph\nsd/ }" file
在这里,我们只匹配行,直到第一个匹配的"sd"为止,因此以后的所有sd都将不匹配.
Here, we only match lines until the first matching "sd", so any later sd's will not match.
这篇关于有什么方法可以获取匹配的图案线的行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!