Skip to content

Instantly share code, notes, and snippets.

@miku
Last active December 23, 2015 10:29
Show Gist options
  • Save miku/bc8315b10413203b31de to your computer and use it in GitHub Desktop.
Save miku/bc8315b10413203b31de to your computer and use it in GitHub Desktop.
filter file by line number
#!/bin/bash
#
# filterline keeps a subset of lines of a file.
#
# cf. http://unix.stackexchange.com/q/209404/376
#
set -eu -o pipefail
if [ "$#" -ne 2 ]; then
echo "Usage: filterline FILE1 FILE2"
echo
echo "FILE1: one integer per line indicating line number, one-based, sorted"
echo "FILE2: input file to filter"
exit 1
fi
LIST="$1" LC_ALL=C awk '
function nextline() {
if ((getline n < list) <=0) exit
}
BEGIN{
list = ENVIRON["LIST"]
nextline()
}
NR == n {
print
nextline()
}' < "$2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment