Search code examples
linuxawksedtext-manipulation

How can I split a text file line by line into 2 text files by delimited column?


I've tried various combinations of the following:

awk -F" ||| " '{$0=$1}1' source_file.txt > column1.txt
awk -F" ||| " '{$0=$1}2' source_file.txt > column2.txt

or

awk 'BEGIN {FS=" ||| ";}{print $1}' source_file.txt > column1.txt
awk 'BEGIN {FS=" ||| ";}{print $2}' source_file.txt > column2.txt

Instead of the desired output, I either get the entire line (ex. foo bar ||| baz) or I get only the first word (ex. foo).

If you'd like to help, here is a sample text file:

source_file.txt

foo bar ||| baz
qux ||| quux
corge grault ||| garply waldo
fred |||
xyzzy ||| thud

And here's the desired output:

column1.txt

foo bar
qux
corge grault
fred
xyzzy

column2.txt

bar
quux
garply waldo

thud

Solution

  • awk -F' \\|\\|\\| ?' '{print $1 > "column1"; print $2 > "column2"}' file
    

    or more generally

    awk -F' \\|\\|\\| ?' '{for(i=1;i<=NF;i++) print $i > "column"i}' file