0

I have multiple sequenced txt-files. They have specific data which I need to gather in one output file.

For Example:

1.txt

     Colour:    Red

     Hight:     10

2.txt

     Colour:    Blue

     Hight:     12

How can I use bash commands, such as sed/grep, to search for specific words and ignore some charachters in order to get the data, and put them in one output file.

For example:

out.txt

     Colour    Hight

      Red        10

      Blue       12

Thanks for helping Anees

2
  • 2
    What have you tried so far? "ignore some charachters" Which characters do you want to ignore? – John1024 Oct 29 '15 at 0:14
  • 1
    Are we assuming always 2 lines per input file, always in the same order? – RobertL Oct 29 '15 at 0:15
1

Assuming there are always 2 fields per file and always in the same order, Here's one way to do it with sed:

#!/bin/sh

printf '%s\t%s\n' Colour Hight

sed '

    / *Colour: */ {
        s///
        h
        n
    }

    / *Hight: */ {
        s///
        G
        s/\n/\t/g
    }

' "$@"

This answer uses the hold space feature of sed to save the data values from one line to the next.

We use statement grouping with { and }. All the commands in the group apply only to the addressed lines, in this case the lines selected by the patterns / *Colour */ and / *Hight */.

On both the Colour and Hight lines, we first delete the text that was matched (*Colour * or *Higth *) with s///.

On the Colour line, we then hold h the remaining text in the hold space, and then skip to the next line of input without printing (n).

On the Hight line, we get/append G the contents of the hold space to the pattern space, concatenated with a newline '\n' by sed. We then subsitute a tab \t for this newline and sed prints the output.

This answer should work with all versions of sed, whether on Linux, FreeBSD, or OS X.

0

You can put the header of the output file like
echo 'Colour Hight' > out.txt
And then for each file you can do something like:
awk '{printf $2" ";next;}' 1.txt >> out.txt
Or for all the txt files you can do:
ls *.txt | xargs awk '{printf $2" ";if (++onr%2 == 0) print "";next;}' >> out.txt

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.