Create multiple files from single file based on row separator

Hello ,

Can anyone please help me to solve the below -

Input.txt

source table abc
col1 char
col2 number
source table bcd
col1 date
col2 char

output should be 2 files based on the row separator "source table"

abc.txt

col1 char
col2 number

bcd.txt

col1 date
col2 char

Please suggest .

Thanks

You have asked for our help 68 times before... What have you tried to solved this problem?

What operating system are you using?

What shell are you using?

Done below -

#!/bin/sh

while read line
do
   if echo $line | grep source; then
       line_no=`echo $line | sed 's/source\([0-9]*\)/\1/g'`
   elif echo $line | grep END; then
       : #ignore
   else
       echo $line >> out.$line_no.txt
   fi
done < input_split.txt

Any smarter approach ?

Well, How about this?

awk '/source/{file=$3".txt";next;}!/END/{print $0 >>file}' input_split.txt

-Ranga

Your post #1 didn't say anything about ignoring lines containing the string END as the code above does, said you wanted output files abc.txt and bcd.txt instead of the files produced by the above code ( out. table abc.txt and out. table bcd.txt ), will convert any sequence of one or more spaces and/or tabs to a single space character (which is not what I expected from the sample you provided), and is processing a file named input_split.txt instead of the file Input.txt that you said you wanted to process.

To get something closer to what you said you wanted, you might try something more like:

#!/bin/sh
awk '
/^source table/ {
	if(fn)	close(fn)
	fn = $NF ".txt"
	next
}
{	print > fn
}' Input.txt

You didn't answer my question about what operating system you're using. If you're using a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk or nawk .

simple bash

while read -a arr ; do
if [ -n "${arr[2]}" ]
then x=${arr[2]}
else
echo ${arr[@]} >> "$x"
fi
done < file

. All these files need to be closed, but don't know where to put close

Unlike the open() system call (which opens the lowest available file descriptor), the shell file redirection operation >> "$x" closes standard output (file descriptor 1) if it is currently open and opens the file named by the expansion of $x as as file descriptor 1 with the append flag set.

If for some reason you are opening files with different file descriptors (instead of reusing a single file descriptor), you can close standard input with <&- , close standard output with >&- , close an input file using file descriptor n with n<&- , and close an output file using file descriptor n with n>&- .

1 Like