Find the answer to your Linux question:
Results 1 to 2 of 2
I was wondering how you would replace certain text with a new line in a sed expression. Such as in output="this is a test" output=`echo $output | sed 's/is/\n/'`; echo ...
  1. #1
    Just Joined!
    Join Date
    Mar 2009
    Posts
    31

    New Line in Sed expression

    I was wondering how you would replace certain text with a new line in a sed expression. Such as in

    output="this is a test"
    output=`echo $output | sed 's/is/\n/'`;
    echo $output

    and the output is

    this
    a test

    Is there a way to do this? I know getting the new line character in scripts is difficult and I thought using the -e switch with echo might solve it but it didn't. Any other ideas?

    - John

  2. #2
    drl
    drl is offline
    Linux Engineer drl's Avatar
    Join Date
    Apr 2006
    Location
    Saint Paul, MN, USA / CentOS, Debian, Solaris, SuSE
    Posts
    1,117
    Hi.

    Noting that "is" occurs first in "this", the result depends on quoting or the lack of it.
    Code:
    #!/usr/bin/env bash
    
    # @(#) s1       Demonstrate sed and quoting.
    
    echo
    set +o nounset
    LC_ALL=C ; LANG=C ; export LC_ALL LANG
    echo "Environment: LC_ALL = $LC_ALL, LANG = $LANG"
    echo "(Versions displayed with local utility \"version\")"
    version >/dev/null 2>&1 && version "=o" $(_eat $0 $1) sed
    set -o nounset
    
    echo
    echo " Results:"
    output="this is a test"
    echo $output | sed  's/is/\n/'
    
    echo
    x=`echo $output | sed  's/is/\n/'`
    echo $x
    
    echo
    x=`echo $output | sed  's/is/\n/'`
    echo "$x"
    
    echo
    x=$( echo $output | sed  's/is/\n/' )
    echo "$x"
    
    exit 0
    Produces:
    Code:
    % ./s1
    
    Environment: LC_ALL = C, LANG = C
    (Versions displayed with local utility "version")
    OS, ker|rel, machine: Linux, 2.6.11-x1, i686
    Distribution        : Xandros Desktop 3.0.3 Business
    GNU bash 2.05b.0
    GNU sed version 4.1.2
    
     Results:
    th
     is a test
    
    th is a test
    
    th
     is a test
    
    th
     is a test
    The pages at Quoting may help ... cheers, drl
    Welcome - get the most out of the forum by reading forum basics and guidelines: click here.
    90% of questions can be answered by using man pages, Quick Search, Advanced Search, Google search, Wikipedia.
    We look forward to helping you with the challenge of the other 10%.
    ( Mn, 2.6.n, AMD-64 3000+, ASUS A8V Deluxe, 1 GB, SATA + IDE, Matrox G400 AGP )

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...