What is the significance of -n parameter passed to sed command?

天涯浪子 提交于 2020-05-24 02:46:48

问题


Can someone please tell me how does sed -n '1!p work ? Below is the full command which I am using to sort my pods in k8s based on nodes they are assigned.

kubectl get pods -o wide --all-namespaces|sort -k8 -r| sed -n '1!p'

The above command works perfectly and the sed part removes the first header line from the final output.

I want to understand how does the sed part work and what's the significance of the parameters passed to sed?


回答1:


From info sed:

-n: By default, 'sed' prints out the pattern space at the end of each cycle through the script (*note How 'sed' works: Execution Cycle.). These options disable this automatic printing, and 'sed' only produces output when explicitly told to via the 'p' command.

1p: print first line

1!p: do not print first line.




回答2:


By default, sed will output every line it parses.
-n option is there to hide this output, and display only the lines specified with the p option.

In your exemple, sed -n '1!p' means "Display every line but first".


A more understandable example is when you want to search/replace with sed. If you want to see the whole resulting file you'll use this:

sed 's/from/to/g' file.txt

But if you only want to see which lines have been changed, use this:

sed -n 's/from/to/gp' file.txt


来源:https://stackoverflow.com/questions/58779782/what-is-the-significance-of-n-parameter-passed-to-sed-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!