In the previous example, you saw that input passed into sed with substitute operation would print the results directly to standard output.
Let’s explore sed’s explicit print command, which you specify by using the option 'p'.
Again, we are using the same test.txt file as an input to print the lines. To do so, run the command "sed 'p' test.txt".
Run the command "sed -n '1~3p' test.txt". This will print the first line and fourth line and so on till the file exhausted. Here '1 ' represents the starting number of the line and '3' represents three lines jump from first line we would to like retrieve.
For instance, '50~5p' matches line number 50, 55, 60, 65, and so on until file data exhausted.
Printing lines based on the pattern from a file
A pattern range can be a simple text or a complex regular expression. Let us take an example. I have a file called "Rahul.txt" and I would like to print the lines which contains the text "cricket".
Run the command "sed -n '/cricket/p' Rahul.txt"
Just to let you know that this will not look exactly "cricket" word alone and it will print "cricket*" as well. * represents any characters after cricket. Let us see another example with the same "Rahul.txt" file. This time we can look for "Depend" word from the file.
As you see the result prints the line which has "Dependable".
Printing few lines (ranges) based on the pattern from a file
Let us see an example with the same "Rahul.txt" file. This time, we can look from the line which has "Karnataka" word to end of the file. To do so, run the command"sed -n '/Karnataka/,$p' Rahul.txt". Remember this command will always consider for the first match and then process till last line as its mentioned $.
Let us see another example with the same "Rahul.txt" file. This time, we can look from the line which has "Karnataka" word and retrieve three lines after that. To do so, run the command
"sed -n '/Karnataka/,+3p' Rahul.txt"
Let us see another example with the same "Rahul.txt" file. This time, we can look from the line which has "Karnataka" word and retrieve until tenth line. To do so, run the command
"sed -n '/Karnataka/,10p' Rahul.txt"
Let us see another example with the same "Rahul.txt" file. This time, we can look from the line which has "gentleman" word and retrieve until another line contains "Karnataka" . To do so, run the command
"sed -n '/gentleman/, /Karnataka/p' Rahul.txt"
Hope you now understand how sed prints the line from the file based on the given condition 😀.
No comments:
Post a Comment