Skip to content

Instantly share code, notes, and snippets.

@jrsonline
Last active August 12, 2020 15:08
Show Gist options
  • Save jrsonline/b170728287824bd58e2701372e6abfdb to your computer and use it in GitHub Desktop.
Save jrsonline/b170728287824bd58e2701372e6abfdb to your computer and use it in GitHub Desktop.
Split a file into named files
#!/bin/bash
# Given a text file like this:
# /* HEADER */
# import x
# import y
# /* END HEADER */
# ...code...
# /* TO: codeFile.swift */
# ...more code...
# /* DONE */
# ...yet more code...
# /* TO: codeFile2.swift */
# ...even more code...
# /* DONE */
# * APPEND: codeFile.swift */
# ...yay more code...
# /* DONE */
#
# Output will be 2 files , 'codeFile.swift' and 'codeFile2.swift' with content:
# codeFile.swift
# --------------
# import x
# import y
# ...more code...
# ...yay more code...
#
# codeFile2.swift
# ---------------
# import x
# import y
# ...even more code...
#
#
# The original file minus the moved sections is output to the terminal. Note that the header remains.
# Terminal output
# ---------------
# import x
# import y
# ...code...
# ...yet more code...
#
#
# - Original file is NOT changed
# - TO: files must be unique, any existing file is deleted. Use APPEND: to add to an existing file (which could be
# created by an earlier TO:)
FILENAME=$1
awk -F' ' 'BEGIN{file="";pr=1}; /\/\* HEADER/{system("rm -f _header"); file="_header";pr=0}; /\/\* TO:/{file=$3; pr=0;system("rm -f " file); system("cat _header > " file)}; /\/\* APPEND:/{file=$3;pr=0}; /\/\* DONE/{file="";pr=0};/\/* END HEADER/{file="";pr=0};{if (file!="" && pr==1) {print $0 >> file; if (file=="_header") {print $0}} else if (file=="" && pr==1) { print $0};; pr=1}' $FILENAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment