Ryan
Ryan

Reputation: 15270

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

Upvotes: 0

Views: 36

Answers (2)

bsd
bsd

Reputation: 2727

You could try

cat /tmp/a | tr -s '|' | cut -d'|' -f1 #for part 1

cat /tmp/a | tr -s '|' | cut -d'|' -f2 | sed -E "s/^[[:space:]]+//g" #for part 2

The tr flag squeezes delimiters together.

Upvotes: 0

karakfa
karakfa

Reputation: 67567

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

Upvotes: 4

Related Questions