sed — filter lines and more
Print nth line of an input
Use a pipe to generate multi-line input:
# print the 4th line of the reflog
git reflog | sed -n -e "4p"
sed can read a file directly as well:
# print 5th line of a file
sed -n -e "5p" my_log_beautiful_file.txt
Print or skip range of lines
While programming, I often search for object names across many projects. When I find the desired files, I often want to perform operations on a subset of the results. Let’s say I want to open 100 files while skipping the first 5.
Let’s start by finding all *.java and *.xml files that contain the strings foo and bar. Typically, my spell looks like this:
find . -iname '*.java' -o -iname '*.xml' | xargs grep -irl 'foo' | xargs grep -irl 'bar'
Then apply filtering:
# filter
find . -iname '*.java' -o -iname '*.xml' | xargs grep -irl 'foo' | xargs grep -irl 'bar' | sed '5,105!d'
# open files with kwrite
find . -iname '*.java' -o -iname '*.xml' | xargs grep -irl 'foo' | xargs grep -irl 'bar' | sed '5,105!d' | xargs kwrite
Meaning of the sed expression:
5- start at the 5th line105- stop at the 105th line!- negate the address ranged- delete matching lines, print what is left
Similarly, if you want to keep everything except 100 lines starting from the 5th, then just remove !.
find . -iname '*.java' -o -iname '*.xml' | xargs grep -irl 'foo' | xargs grep -irl 'bar' | sed '5,105d'