Ion Pop
Ion Pop

Reputation: 69

Linux split a file in two columns

I have the following file that contains 2 columns :

A:B:IP:80                  apples    
C:D:IP2:82                 oranges    
E:F:IP3:84                 grapes

How is possible to split the file in 2 other files, each column in a file like this:

File1

A:B:IP:80    
C:D:IP2:82    
E:F:IP3:84

File2

apples
oranges
grapes

Upvotes: 2

Views: 2045

Answers (3)

ghoti
ghoti

Reputation: 46826

Here's an awk solution that'll work with any number of columns:

awk '{for(n=1;n<=NF;n++)print $n>"File"n}' input.txt

This steps through each field on the line and prints the field to a different output file based on the column number.

Note that blank fields -- or rather, lines with fewer fields than other lines, will cause line numbers to mismatch. That is, if your input is:

A 1
B
C 3

Then File2 will contain:

1
3

If this is a concern, mention it in an update to your question.


You could of course do this in bash alone, in a number of ways. Here's one:

while read -r line; do
  a=($line)
  for m in "${!a[@]}"; do
    printf '%s\n' "${a[$m]}" >> File$((m+1))
  done
done < input.txt

This reads each line of input into $line, then word-splits $line into values in the $a[] array. It then steps through that array, printing each item to the appropriate file, named for the index of the array (plus one, since bash arrays start at zero).

Upvotes: 1

xxfelixxx
xxfelixxx

Reputation: 6592

Perl 1-liner using (abusing) the fact that print goes to STDOUT, i.e. file descriptor 1, and warn goes to STDERR, i.e. file descriptor 2:

 # perl -n means loop over the lines of input automatically
 # perl -e means execute the following code
 # chomp means remove the trailing newline from the expression

 perl -ne 'chomp(my @cols = split /\s+/); # Split each line on whitespace
           print $cols[0] . "\n";
           warn  $cols[1] . "\n"' <input 1>col1 2>col2

You could, of course, just use cut -b with the appropriate columns, but then you would need to read the file twice.

Upvotes: 1

John1024
John1024

Reputation: 113814

Try:

awk '{print $1>"file1"; print $2>"file2"}' file

After runningl that command, we can verify that the desired files have been created:

$ cat file1
A:B:IP:80
C:D:IP2:82
E:F:IP3:84

And:

$ cat file2
apples
oranges
grapes

How it works

  • print $1>"file1"

    This tells awk to write the first column to file1.

  • print $2>"file2"

    This tells awk to write the second column to file2.

Upvotes: 3

Related Questions