match end of line in bash

match end of line in bash

am 07.01.2008 17:33:36 von artix

Hi All,

I have the following situation:

var="line 1
line 2
line 3"
....

I want to replace the end of line chars (LF) with a "_". I want this to
be a bash only solution and the following does not work:

echo ${var//\012/_}

Any ideas? Thanks.

--
artix
http://www.abstractart.ws _Abstract Art Directory_

Re: match end of line in bash

am 07.01.2008 17:45:45 von Icarus Sparry

On Mon, 07 Jan 2008 17:33:36 +0100, artix wrote:

> Hi All,
>
> I have the following situation:
>
> var="line 1
> line 2
> line 3"
> ...
>
> I want to replace the end of line chars (LF) with a "_". I want this to
> be a bash only solution and the following does not work:
>
> echo ${var//\012/_}
>
> Any ideas? Thanks.

echo "${var//$'\n'/_}"

Re: match end of line in bash

am 07.01.2008 17:49:17 von Stephane CHAZELAS

On Mon, 07 Jan 2008 17:33:36 +0100, artix wrote:
[...]
> I have the following situation:
>
> var="line 1
> line 2
> line 3"
> ...
>
> I want to replace the end of line chars (LF) with a "_". I want this to
> be a bash only solution and the following does not work:

bash only? You understand a shell is a command interpreter
before all, right?

> echo ${var//\012/_}

printf '%s\n' "${var//$'\n'/_}"

this should work in zsh and ksh93 as well (those syntaxes come
from ksh93)

Or POSIXly:

set -f
IFS='
'
set -- $var
IFS=_
newvar="$*"

(that squeezes several NLs into 1 "_").

Strange that you should have shell variables with several lines
in them. Smells like you script could be written in a more
shell-oriented way.

--
Stephane

Re: match end of line in bash

am 07.01.2008 18:05:19 von Luuk

"artix" schreef in bericht
news:478254bd$0$2096$edfadb0f@dtext02.news.tele.dk...
> Hi All,
>
> I have the following situation:
>
> var="line 1
> line 2
> line 3"
> ...
>
> I want to replace the end of line chars (LF) with a "_". I want this to be
> a bash only solution and the following does not work:
>
> echo ${var//\012/_}
>
> Any ideas? Thanks.
>
> --
> artix
> http://www.abstractart.ws _Abstract Art Directory_

script:
#!/bin/bash

var="line 1# line 2# line 3"
echo -e "1: $var"

var=${var//\#/'\012'}
echo -e "2: $var"

var=${var//'\012'/_}
echo -e "3: $var"


output of this:
1: line 1# line 2# line 3
2: line 1
line 2
line 3
3: line 1_ line 2_ line 3