LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Bash question (https://www.linuxquestions.org/questions/linux-general-1/bash-question-547654/)

armandino101 04-20-2007 01:38 PM

Bash question
 
Hi,

say you have a file like this:

Code:

-- comment 1
This
is
the first
line

-- comment 2
This is the
second line

-- comment 3
And this is the third

and you want to generate this


Code:

-- comment 1
This is the first line

-- comment 2
This is the second line

-- comment 3
And this is the third

What's the easiest/shortest way to do this?

Thanks advance,
A.

druuna 04-20-2007 02:27 PM

Hi,

Don't know if this is easy or even short (enough), but it works:
Code:

#!/usr/bin/perl
# splitter.pl
# Usage: splitter.pl <infile>

use strict;
use warnings;

my $inFile="$ARGV[0]";

open(FH,$inFile);
while (<FH>) {
  chomp;
  print "$_\n" if ( /^-- comment/ );
  print "$_ "  if ( !/^-- comment/ );
  print "\n\n" if ( /^$/ );
}

close FH;

I could not come up with a one-liner.........

Hope this helps.

drawde83 04-20-2007 03:03 PM

ok this almost works

Code:

cat comment.txt|sed '/^[[:alpha:]]/N;s/\n/ /'

druuna 04-20-2007 03:57 PM

Hi again,

Here's a (semi) one-liner:
Code:

cat infile | tr "\n" " " | sed -e 's/\(-- comment [1-9][0-9]* \)/\1\
/g' -e 's/  -/\
\
/g'

I like the perl script a lot better, but this one can be executed from the command line......

drawde83 04-20-2007 03:58 PM

It's not pretty and it can probably be made simpler but it's all on one line and it works.
Code:

cat comment.txt|tr '\n' ' '| sed -e 's/--/\n\n--/g' -e "s/\([[:digit:]]\)/\1\n/g"

druuna 04-20-2007 04:02 PM

ROFL

Almost the same solution within the minute :)

drawde83's version using \n in the sed statement could fail on certain platforms, that's why I choose the 'multi-line' one-liner....

If it works on your platform, use that one.

armandino101 04-24-2007 12:18 PM

Thanks for the replies!

drawde, your first script almost works like you said.. :)

druuna, I should have also mentioned that comment 1, 2, 3 can be anything and doesn't have to end with a digit. Basically if a string starts with '--' it's a comment.

The file actually represents a long sql script where i need to strip off the formatting, ie the new lines. If you have any other ideas please post!


All times are GMT -5. The time now is 09:43 PM.