ddrew78 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I have a simple question to which I just can't seem to find the answer. First, here is what my file looks like (after several "sed" commands have already been executed):
policy-map ipcos-abcde16 class abcde16-Queue1 priority police rate percent 35 class abcde16-Queue2 bandwidth 25 class abcde16-Queue3 bandwidth 15
I am trying to insert a simple line break after the word "priority", so it would look like this:
policy-map ipcos-abcde16 class abcde16-Queue1 priority police rate percent 35 class abcde16-Queue2 bandwidth 25 class abcde16-Queue3 bandwidth 15
I have tried several variations of this command, but I either get nothing or a "sed: command garbled: s/priority/priority" error. I truly only need help with this one line :-(
system "sed 's/priority/priority\n\/' cos2 > cos4"; system "mv cos4 cos2";
And, before anybody asks, yes I am using strict and warnings. Any help would be appreciated.

Replies are listed 'Best First'.
Re: inserting line break
by mr_mischief (Monsignor) on Apr 15, 2009 at 16:38 UTC

    Why shell to sed at all?

    while ( <> ) { s/priority /priority\n/; print; }

    If you want it all in one line:

    perl -i~ -pe 's/priority /priority\n/'

    That second when given cos2 as an argument will read the input from cos2, write the output into cos2, and save the original contents as cos2~.

    You might want to see s/PATTERN/REPLACEMENT/msixpogce, perlre, perlrun (for the one-liner options), and perltrap which covers traps for people coming from awk, sed, C, and other languages.

      Thanks, that worked perfectly.
Re: inserting line break
by jethro (Monsignor) on Apr 15, 2009 at 16:51 UTC
    mr_mischiefs advice of using perl is really (really) the way to go. But to soothe your curiosity the error message is because of ...ity\n\/' which presumably should be ...ity\\n/'
Re: inserting line break
by Bloodnok (Vicar) on Apr 15, 2009 at 17:30 UTC
    Using sed(1) to modify EOL chars is, AFAIR, only possible iff you've accumulated a number of lines (by appending them in, using the H command, to) the hold space e.g. the following will cause all lines in file to be output on the same line:
    # sed -n 'H;$x;$s,\n,,gp' file ^ ^ ^ ^ | | | | | | | | | | | For the last line only, globally strip all line ending +s in the pattern space and print the result | | | | | For the last line only, swap the hold and pattern spaces | | | Append each line to the hold space | Don't print any lines - by default all lines are printed follow +ing processing
    A user level that continues to overstate my experience :-))