If you really need to do it using Bash or a POSIX shell,
Code:
#!/bin/sh
if [ $# -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo ""
echo "Usage: $0 [ -h | --help ]"
echo " $0 OUTPUT [ INPUT(s)... ]"
echo ""
echo "This will split the input after lines containing only"
echo "a slash (/) into separate files. The first output file"
echo "will be OUTPUT.1, the second OUTPUT.2, and so on."
echo "The slash will be the last line in each output file"
echo "(except possibly the last file, if there is no trailing slash)."
echo ""
exit 1
fi
BASE="$1"
shift 1
cat "$@" | (
COUNT=1
exec >"$BASE$COUNT"
LINE=''
while read -r LINE || [ -n "$LINE" ]; do
echo "$LINE"
if [ "$LINE" = "/" ]; then
if [ -s "$BASE$COUNT" ]; then
COUNT=$[COUNT + 1]
exec >"$BASE$COUNT"
fi
fi
LINE=''
done
exec >/dev/null
[ -s "$BASE$COUNT" ] || rm -f "$BASE$COUNT"
)
Save in a file, make it executable, and run it without parameters to see the usage: The first parameter is the base name to which the proc number is appended to get the output file names, and the rest of the parameters are input file names. If there are no input file names, it expects input from standard input, so you can use it as a pipe too.
The way this one works is:
The first if..fi clause checks if there is at least one parameter, the output base filename. If there are no parameters, or only -h or --help is given, the terse usage is printed, and the script aborts.
The first parameter is saved in BASE, and removed from the positional parameters using
shift 1 . This way
"$@" will expand to the rest of the parameters given to the script, but not include BASE.
The
cat command outputs all specified input files, or if none, the standard input. This is one of the rare valid uses for cat before a pipe. The output is redirected to a subshell (the bit in parentheses).
The subshell uses
exec >filename to redirect future output by any command in that subshell to a file.
The while loop reads each input line into LINE. It looks a bit weird because this way it works right even if the final line does not contain a newline. (Clearing the LINE to an empty string is part of that trick.)
The loop body just echoes the line just read. Because we've redirected output, it ends up in some file.
If the line contains only a slash, the nested if clause within the loop body checks if the file is not empty (
[ -s filename ] is true only if the file contains something). If it contains anything, we increase the count, and redirect output to a new file.
This extra check is to avoid you getting extra empty files.
Finally, the subshell redirects output to a black hole (/dev/null, goes nowhere!), and checks if the last file we've redirected output to is empty. If it is empty, we remove it. Again, this is to just avoid getting extra empty files.
That's about it. Note, however, that I haven't tested the above, just written it blindly; it might have bugs in it. You must check it before use!