我需要帮助来理解以下代码。为什么N和D在这里使用?他们在这里是什么意思?
这是一个sed
命令,用于打印重复的输入行。
sort file | sed '$!N; s/^\(.*\)\n\1$/\1/; t; D'
答案 0 :(得分:2)
这是脚本的翻译:
for each line of input: # sed does this loop automatically
if it's not the last line: # This is what $! means
append a \n (newline) to the current line # N means this
append the next line of input to the current line # and this
# Note that the "current line" may now contain a \n in the middle!
if the current line matches some string, followed by a \n,
followed by that same string again: # s command's pattern
delete the \n and the second copy of the string # s command's action
if the s command matched: # t means this
go to endOfScript # and this
delete everything up to the first \n in the current line # D means this
go to endOfLoop # and this
endOfScript:
print the current line, followed by \n, to stdout # sed does this automatically
endOfLoop:
# just return to the top of the loop for the next line of input
D命令实际上有点复杂:如果当前行还剩下任何字符,它会抑制循环顶部下一行的读取。但是在这个sed脚本中情况并非如此。
答案 1 :(得分:1)