0

I have a large text file abc.txt with the following format:

BALT
-6.110
130.600
4.06874414
-0.03254425
BALT
-6.620
154.460
3.92286595
-0.17842244
BARM
32.740
140.680
3.94326190
-0.15802649

I need this file to convert an output file xyz.txt in the format like:

BALT 1
 -6.110 130.600
 4.06874414
 -0.03254425
BALT 2
 -6.620 154.460
 3.92286595
 -0.17842244
BARM 3
 32.740 140.680
 3.94326190
 -0.15802649

The numbers 1, 2, 3... after four character data name will increase as I go for more data.

| improve this question | | | | |
2

Here's a oneliner:

# sed 's/^[A-Z]/>&/' abc.txt | awk -v RS='>' 'NR>1 {printf("%s %d\n %s %s\n %s\n %s\n",$1,NR-1,$2,$3,$4,$5)}' > xyz.txt

Here's the output generated:

# cat xyz.txt 
BALT 1
 -6.110 130.600
 4.06874414
 -0.03254425
BALT 2
 -6.620 154.460
 3.92286595
 -0.17842244
BARM 3
 32.740 140.680
 3.94326190
 -0.15802649

The details:

First part - the sed part of the line adds an arbitrary special character to the start of each record (a record is a name followed by 4 numbers). I picked a '>' to start the record. This makes the processing by awk easy.

Second part - For each record, just print out a new format of the fields as you specified. The only quirk is that there's an extra blank record at the start - we skip over that (NR>1).

| improve this answer | | | | |
  • Nice answer. The only thing I'd consider adding (if it didn't break any other programs/script that use this file) is an extra \n after each record. That adds a useful record-separator for any future processing. – cas Oct 23 '15 at 22:50
1

There are 2 tasks: numerate apropriate line(s) than format output:

nl -bp[A-Z] -nln abc.txt | 
sed '
     /^\w/{
           s/\(.*\)\(....\)/\2 \1/
           n
           N
           s/\n\s*/ /
          }
     s/^\s*/ /
    ' > xyz.txt

Or if you like awk

awk '
     /[A-Z]/ {
             print $0, ++count
             getline
             printf " %s", $0
             next
     }
     {
             print "", $0
     }
    ' abc.txt > xyz.txt
| improve this answer | | | | |

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.