Skip to content

Instantly share code, notes, and snippets.

@peterwwillis
Created October 28, 2020 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterwwillis/1be9836291ad967a71d29c038a25ddeb to your computer and use it in GitHub Desktop.
Save peterwwillis/1be9836291ad967a71d29c038a25ddeb to your computer and use it in GitHub Desktop.
Unix Tips And Tricks

Awk

Print only the first part of a file separated by two newlines

Note that this uses tr to remove any carriage-returns (as in "\r\n" from Windows or network programs)

# Print only the block of lines before the first double-newline
cat file.txt | tr -d '\r' | \
  awk 'BEGIN {RS="\n\n"} NR==1'
  
# Print every block of lines after the first double newline
cat file.txt | tr -d '\r' | \
  awk 'BEGIN {RS="\n\n"} NR>=2'

And here's a very ugly version of the same using multi-dimensional arrays. Set 'z=' to the index you want to print. In this example, it'll print the second block of lines after the first double-newline. (note that this is removing the empty line using getline)

cat file.txt | tr -d '\r' | \
  awk 'BEGIN {i=0; n=0; z=1}; 
       $0 ~ /^$/ { n++; getline; }; { a[n][i]=$0; i++ };
       END { for(i in a[z]) print a[z][i] }'

Useful Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment