Quote:
Originally Posted by marvs
If test.txt is:
first
second
third
the following works for in a BASH (at least) script, so long as LIN doesn't exhaust ENVIRONMENT reserve.
#!/bin/bash
LIN=$(cat test.txt)
echo $LIN > lintest.txt
# end
cat lintest.txt should show:
first second third
|
First of all, please use
[code][/code] tags around your code and data, to preserve formatting and to improve readability. Please do not use quote tags, colors, or other fancy formatting.
Next, this doesn't replace newlines with semicolons, as the (now 3-year-old) OP wanted. But admittedly it does remove them.
And the reason this "works" like that is because of the '
echo $LIN' line. Since the variable isn't quoted, the contents of the variable are word-split after expansion, and echo sees each word in the file as a separate value to print.
The problem with using this is that the shell splits values on all contiguous instances of whitespace, not just newlines. It also has an added danger that globbing patterns are expanded as well.
Code:
#line 4 is a blank line
$ cat file.txt
line with single spaces
line with multiple spaces
line with tabs
line with glob *
$ text=$( <file.txt )
$ echo $text
line with single spaces line with multiple spaces line with tabs line with glob file.txt file2 file3
$ echo "$text"
line with single spaces
line with multiple spaces
line with tabs
line with glob *
Quoting the variable preserves all whitespace and other special characters.
You could manually disable globbing and set IFS to newline only to work around most of these issues, but why bother when there are better ways to handle it, as documented above.
Incidentally, here's another method I just thought of that does replace newlines with semicolons, using bash v4's
mapfile command and an array.
Code:
$ shopt -s extquote #you may need to enable this first, esp. in scripts
$ mapfile array <file.txt
$ echo "${array[*]//$'\n'/;}"
line with single spaces; line with multiple spaces; line with tabs; ; line with glob *;
Edit: Actually even a single variable would work; and maybe even better (I see there's an extra space inserted between the "lines" in the above, due to the default IFS setting.
Set IFS to null first to fix that.):
Code:
$ text=$( <file.txt )
$ echo "${text//$'\n'/;}"
line with single spaces;line with multiple spaces;line with tabs;;line with glob *