1

I have a delimited file with the following format that I have assigned to a bash variable "foo":

echo $foo

A  1  hello
B  2  hello
C  3  hello
D  4  world
E  5  world
F  6  world

I am trying to find a preferably awk-based solution that can split this variable into new text files such that all of the rows with identical values in column #3 are in one file. In a perfect world, the files would be named after the string in column #3 In this case, the files would be "hello.txt and "world.txt" with the following contents:

cat hello.txt
A  1  hello
B  2  hello
C  3  hello

cat world.txt
D  4  world
E  5  world
F  6  world

EDIT: I should have included some previous attempts for this as mentioned below. I know how one could do this if the patterns were known ahead of time using something like grep, but am not sure how to allow it to accept wildcards. This is what I normally do if I know I will only need to extract by a very specific pattern.

echo "$foo" | grep -w "hello" > hello.txt
echo "$foo" | grep -w "world" > world.txt
  • You will get a much more friendly reception and much better help here if you show what code you have tried so far, however inadequate, and describe what problems you were having with it. Without code, your question looks like a request for free consulting and many people don't like that. – John1024 Mar 20 at 0:18
  • 2
    Thank you for the advice. I was really quite stuck and couldn't think of any solutions to this, which is why I had no code to show. The only solutions I could come up with required that the pattern be known beforehand, but will post an example as an edit. – adam Mar 20 at 0:24
  • Excellent update. – John1024 Mar 20 at 21:35
4

You should be able to use

   awk '{print > $3 ".txt"}' <<< "$foo"

Ex.

$ echo "$foo"
A  1  hello
B  2  hello
C  3  hello
D  4  world
E  5  world
F  6  world

awk '{print > $3 ".txt"}' <<< "$foo"

$ head {hello,world}.txt
==> hello.txt <==
A  1  hello
B  2  hello
C  3  hello

==> world.txt <==
D  4  world
E  5  world
F  6  world
  • Thank you! That makes sense and works perfectly. – adam Mar 20 at 0:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.