Another.Chemist
Another.Chemist

Reputation: 2559

how to use any bash command to cut a file and save all columns in a different file

Good day,

I was wondering how to cut a file and save each part in a different file. Where the delimiter is ]

example:

TOfile1 ] TOfile2

Thanks in advance

Upvotes: 0

Views: 562

Answers (3)

Digital Trauma
Digital Trauma

Reputation: 15996

This appears to be precisely the standard use-case for the cut utility. Without further ado:

cut --delimiter=']' --field=1 input.txt > TOFile1.txt
cut --delimiter=']' --field=2 input.txt > TOFile2.txt

I'm using the long option names here for readability. The short versions are -d and -f respectively.

Upvotes: 1

jaypal singh
jaypal singh

Reputation: 77085

Using awk:

$ awk -F' []] ' '{for(i=1;i<=NF;i++) print $i > "file"i}' input
$ head file*
==> file1 <==
TOfile1

==> file2 <==
TOfile2
  • Set the delimiter to []], since ] is a special character we put it inside character class to consider it literal.
  • We iterate over all fields storing each element in a separate file. This gives the answer flexibility to create as many files as there are fields and not just two.

Hence, if your input is something like the following:

$ cat input
TOfile1 ] TOfile2 ] Tofile3 ] Tofile4
TOfile1 ] TOfile2

$ awk -F' []] ' '{for(i=1;i<=NF;i++) print $i > "file"i}' input

$ head file*
==> file1 <==
TOfile1
TOfile1

==> file2 <==
TOfile2
TOfile2

==> file3 <==
Tofile3

==> file4 <==
Tofile4

Upvotes: 3

user3159253
user3159253

Reputation: 17455

sed -e 's/.*]//' myfile > TOFile2
sed -e 's/].*//' myfile > TOFile1

Upvotes: 1

Related Questions