PDA

View Full Version : ksh mystery: how are newlines represented in files?


gnome
Dec19-03, 02:14 PM
Please take a look at these lines which demonstrate my problem in a korn shell terminal:

$ var="abc\ndef"
$ print "$var"
abc
def
$ print "$var" > file1
$ var=${var//\\n/}
$ print $var
abcdef
$ var=$(<file1)
$ print $var
abc
def
$ var=${var//\\n/}
$ print $var
abc
def
$

First I defined var with a newline embedded in it. I printed it and, as expected, got
abc
def.
I printed the same thing to file1.

Next, I edited it using the pattern operator ${var//\\n\} to remove the newline, printed it and again got what I expected. Now var is
abcdef

Then, I replaced var with the contents of file1: var=$(<file1)
Printed it, and again there's
abc
def

So far, so good.
Now, I try to edit it again with exactly the same command var=${var//\\n/}
But it has no effect. Var still prints as
abc
def

What's going on here? Is the newline represented differently in file1? How? How can I edit it out?

One other observation:
I noticed that in the FIRST instance, after defining var="abc\ndef", if I entered
print $var
I got
abc def
Only by entering
print "$var"
would I get
abc
def

But after reading it back in from the file, it prints as
abc
def
whether I enter
print "$var"
or
print $var

gnome
Dec19-03, 04:51 PM
Well, I found a solution using the cat -E option that gives me a way to edit out the mystery newline character without knowing exactly what it is. For example:

$ var="abc\ndef"
$ print "$var"
abc
def
$ print "$var" > file1
$ cat file1
abc
def
$ var=$(cat -E file1)
$ print "$var"
abc$
def$
$ var=${var//\$?/}
$ var=${var//\$*/}
$ print "$var"
abcdef

But if anybody knows what that character is & how to edit it out of a variable without going through this merry-go-round procedure, please let me know.