1. Extract Using Line Numbers :
1 2 3 | sed -n '10'p <filename> #Prints 10th line of file sed -n '10,20'p <filename> #Print lines 10 to 20 sed -n '10,$'p <filename> #Print lines 10 to end |
$ sed -n '10'p file is equivalent to
$ sed '10!d' file and results
Line 10
The default output behavior is to print every line of the input file stream.The explicit 10p command just tells it to print the tenth line
So in the first example since sed is called with -n flag, it suppress the default output and prints 10th line
in the second example, (note -n is not used) sed will delete (d) the line if it is not (!) line number 10
Similarly printing lines from 2 to 4 :
1 2 | sed -n '2,4'p file sed '2,4!d' file |
Line 2
Line 3
Line 4
2. Extract Using Pattern :
Some time we may need to print the lines which matches the pattern. that also can be done using sed
1 | sed -n '/main/p' check.cpp |
will print the lines which matches the pattern main in check.cpp file.
grep can be used as an alternative
similarly instead of 'p' (print), 'd' (delete) can be used to delete the line matching the pattern from the file.
1 | sed '/main/d' check.cpp > newfile.cpp |
3. Extract non empty lines :
Following will remove the empty lines from the file. and redirect remaining to new file.
1 2 | sed '/./!d' check.cpp > newfile.cpp sed '/^$/d' check.cpp > newfile.cpp |
0 comments:
Post a Comment