Substituting some characters in a text file (shell script).
Hi:
I have a text file from which I want to eliminate all newlines save in the case where two consecutive newlines are present. That is, one possible algorithm would be the following. Code:
1. p=p+1 # advance character pointer (a) I would begin by making use of a while sentence. (b) I must treat p as a numeric variable. (c) Is readline able to read char by char? (d) And what would be a clause/instruction/sentence to write a file? (e) Would it not be easier to have two files: one input file and one output file? Could you give me some hints covering these points? |
Code:
sed '/^$/d' oldfile > newfile |
I consider myself able to write the script. If only I new how to write one character at a time, in the style of C's fputc, fput, putc and putchar. But by reading the bash manual the only builtin command that does output is printf. On the contrary, for input there is the read builtin command.
|
Code:
$ help read Quote:
Code:
$ echo -n x ; echo -n y ; echo -n z ; echo |
Thanks ntubski. 'read -u fd' reads input from file descriptor fd. But then there must be a write command that writes to a given file descriptor!
|
You can use output redirection (this works for any command, not just echo):
Code:
echo -n x >file # write the character 'x' to "file" |
Yes,
while done < $infile The thing is that I must read/modify a file or, else have the file to modify as input and do output on another file. But I think I now have enough material to begin thinking how I'll do it. Thanks a lot. |
Your original problem statement:
Quote:
Code:
sed -n 'h; :1 n; /./{H; b1}; /^$/p; x; s/\n/ /g; p' oldfile > newfile |
It seems there is no choice for me but getting familiar with sed. Thanks a lot, pixellany. The command seems to work fine.
|
awk version; a bit longer but more readable, I think.
Code:
awk '{if (length($0)) printf("%s ",$0); else print""} END{print""}' oldfile > newfile |
Thank you ntubski. Some day I'll get quite familiar with sed and awk. In the meantime, I'll keep your examples in order to study them in the future. I think that using the given file as input and letting the modified file be another file (output file) I can do it within a while loop and input/output redirection. For instance, for output, I'll use something like
echo -n $var1 >>outfile. |
Code:
semoi@darkstar:~/script/el_mio$ cat f1 |
Hi.
From `help read': Quote:
Code:
IFS="" read -n1 x && echo "[$x]" To preserve newlines as well, add -d "": Code:
while IFS="" read -n 1 -d "" car1 # -n 1 reads only one char |
Quote:
|
Quote:
Seriously, I am jealous of the awk wizards---someday, I'll learn it. |
All times are GMT -5. The time now is 05:25 PM. |