Sunday, May 5, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 33364  / 1 Year ago, tue, may 16, 2023, 6:47:34

I'll use route as an example.



route -n


The above outputs routing information. The top row is your active connection. I can manipulate the output to only the second column by doing:



route -n | awk '{print $2}'


Now, how can I filter by row?


More From » 11.10

 Answers
7

To print a particular line you can use sed:


route -n | sed -n 2p

to print second line.


sed, what is


I will give a short and incomplete explanation of what is sed. For a complete description I suggest to see sed info pages (run info sed).


sed mean stream editor, i.e. an editor that can act on a stream (or pipe) of text data, though it can act also on files; substantially this mean that (differently from ed) it can never turn back to a previous line.


sed, as awk reads one line at a time and apply a script to that line to possibly modify it. At the end of the script, by default the modified line is output to stdout. Then sed go on the the next line.


A script is a sequence of pair address-command, if the line match the address then the command is executed.


The typical use of sed is to perform a substitution of a pattern with something, e.g.


command | sed 's/ *$//'

here the string between single quotes is the script, consisting of a single address-command pair. The address is missing (it would appear before the s), in such a case the command is applied by default to all input lines. s is the command and the rest of the string are command specific instructions, saying "substitute 0 or more occurrence (*) of a space ( ) character at end on line ($) with nothing (i.e. remove them)".


Other useful command are p and d. The p command print the current line, this is useful in combination with the -n option, that modify the default behavior to print the current line at end of script. So in


sed -n '2p'

the script is the string 2p consisting on the address 2 and the command p, so the line 2 will be printed, all other line instead will not be printed, due to the -n option.


The d command delete a line, for example


    sed '3,6d'

would delete all lines from the third to the sixth. 3,6 is an address range. I observe that in this case one should not use the -n option, because we want to print all other lines.


Last thing, an address could be a pattern, like in


sed -n '/^#/p'

this command would print all lines beginning (^) with a # character.


[#41738] Wednesday, May 17, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rinstracte

Total Points: 221
Total Questions: 114
Total Answers: 120

Location: France
Member since Fri, Jan 28, 2022
2 Years ago
rinstracte questions
Wed, Jun 15, 22, 02:09, 2 Years ago
Tue, Jan 24, 23, 01:39, 1 Year ago
Wed, Jun 9, 21, 04:34, 3 Years ago
Sun, Apr 17, 22, 11:38, 2 Years ago
;