Haravikk
Haravikk

Reputation: 3280

Replacing new-lines with more than a single character

Okay, so I know that the best way to replace new-lines is usually to do something like tr '\n' ' ' or similar, however this only works for a single character.

What I'd like to do is replace new-lines, but insert something longer than a single character; in my case I actually want to add a timestamp so that something like this:

foo
bar

Becomes something like this:

[11:30] foo
[11:30] bar

I need to be able to do this by replacing the new-line character itself, as I can't guarantee that the last line of input will be complete at the time I process it (e.g - it could be output from printf '%s' "foo", so has no line-ending yet). This means that using read line-by-line and just echoing with the timestamp added isn't an option.

Upvotes: 0

Views: 68

Answers (2)

Haravikk
Haravikk

Reputation: 3280

I found a bash-specific alternative so I figured I'd show it as an alternative answer for those with a bash shell (which is most people, except those currently suffering shell-shock ;)

#!/bin/bash
NL=$'\n'
data="foo${NL}bar"
printf '%s' "[11:30] ${data//$NL/$NL[11:30] }"

glenn jackman's proposal to use perl may be more portable for systems with other shells, but for bash this avoids the use of another program.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246744

Perl's good for this. Here's a file with no trailing newline:

$ od -c file
0000000   l   i   n   e   1  \n   l   i   n   e   2  \n   l   a   s   t
0000020       l   i   n   e   ,       n   o       n   e   w   l   i   n
0000040   e
0000041
$ perl -0777 -MTime::Piece -pe 's/^/ (localtime)->strftime("[%H:%M] ") /mge' file
[08:39] line1
[08:39] line2
[08:39] last line, no newline⏎

My shell () displays the "⏎" character to indicate no ending newline.

Upvotes: 2

Related Questions