1

I am writing a script that iterates through all the files and replaces line feeds at the beginning of each file. For a file like this,

\n
\n
A line \r\n
Another line \r\n
\r
\f
\n
\n
Few more lines \r\n
\r\n

I need to replace all line feeds at the beginning of the file with CRLF, i.e.

\r\n
\r\n
A line \r\n
Another line \r\n
\r
\f
\n
\n
Few more lines \r\n
\r\n

I tried using,

sed -i 's/^[\n]/\r\n/' file.txt

But it doesn't seem to work.

Edit: I am able to replace a range of lines with,

sed '1,2s/^/\r/'

But is there a way to identify if the first character in the file is line feed?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
mak
  • 113
  • 1
  • 6

1 Answers1

1

If you have GNU sed, then you can use the special address form 0,/./ to make substitutions only in the portion of a file up to the first non-empty line. To illustrate:

~$ cat -e file.txt
$
$
non empty line$
non empty line$
$
$
non-empty line$
$

(the $ signs indicate literal line endings: see man cat); then

~$ sed '0,/./ s/^$/\r/' file.txt | cat -e
^M$
^M$
non empty line$
non empty line$
$
$
non-empty line$
$

where the ^M characters indicate the inserted CRs.

steeldriver
  • 81,074