我想将文本和行号一起插入到与grep语句匹配的文件中。
-----------------------------
-- Ticket #: 10001
-- Subject: my subject
-- Author: janedoe
-----------------------------
-----------------------------
-- Ticket #: 10002
-- Subject: my subject2
-- Author: janedoe2
-----------------------------
所以我想要grep“ - Ticket”这个词,并在其上面添加两行相应的行号。
PROMPT Line 1
-----------------------------
-- Ticket #: 10001
-- Subject: my subject
-- Author: janedoe
-----------------------------
PROMPT Line 8
-----------------------------
-- Ticket #: 10002
-- Subject: my subject2
-- Author: janedoe2
-----------------------------
所以我可以插入随机字符,但我无法弄清楚如何获取行号。
sed '/-- Ticket/i\
ssssssss
$H
x' < finalfile.txt
答案 0 :(得分:2)
使用awk
即可:
awk -v RS= '/-- Ticket/{++i; print "PROMPT Line ", i ORS $0 ORS; i+=split($0, a, /\n/)+1}' file
PROMPT Line 1
-----------------------------
-- Ticket #: 10001
-- Subject: my subject
-- Author: janedoe
-----------------------------
PROMPT Line 8
-----------------------------
-- Ticket #: 10002
-- Subject: my subject2
-- Author: janedoe2
-----------------------------
awk
使用空RS
拆分输入数据,从而在单独的记录中为我们提供完整的票证部分。split
,我们可以计算每个部分中有多少行,并计算PROMPT Line
答案 1 :(得分:1)
鉴于格式描述,不需要专门查看-- Ticket
;相反,我们可以在一行空格后立即查找一行破折号(构成一个章节标题)。
这更容易,因为它减少了所需的回溯量,从而避免了缓冲内容的需要。
#!/bin/bash
lineno=0 # track our line number
in_section=0 # track whether we're already in a section
section_header='-----------------------------'
while IFS= read -r line; do # read the file line-by-line
((++lineno)) # increment our counter
if [[ $line = "" ]]; then # if we see an empty line...
in_section=0 # ...then we're not in a section
elif [[ $line = "$section_header" ]]; then # if we see a header...
if (( in_section == 0 )); then # ...and we're not in a section already
echo "PROMPT Line $lineno" # ...then write a section header
((++lineno)) # ...increment our lineno for that header
in_section=1 # ...and don't process the header on exit
fi
fi
printf '%s\n' "$line" # finally, write our line to output
done
有关以这种方式逐行读取文件的讨论,请参阅BashFAQ #1。