Newline to space code removes 0 from the first line

I am having a peculiar problem. First I run the code below to append 0 at the start of each line in some hundreds of files that I have in a directory. These files have each word in a newline.

for f in *.dat; do
  echo "0" > tmpfile
  cat $f >> tmpfile
  mv tmpfile $f
done

Then I run this script to remove all the newlines, and convert them into space.

ls -1 *.dat | while read page
do
cat $page | awk '$1=$1' ORS=' ' $page > $page.txt
done

But I find that when the second code is run, it removes the 0's that I have put using the first code. Any idea how can this be corrected? But when I put any number greater than 0, the second code does not remove that number. I am using Linux with BASH.

It shouldn't be causing a problem, but the cat in

cat $page | awk '$1=$1' ORS=' ' $page > $page.txt

is redundant - you're passing the filename to awk as a parameter anyway.

1 Like

Yes, "cat" was redundant. It was not needed anyway. But even after removing cat $page in the second script, the same problem of 0 getting removed still persists.

show sample input and expected output.

'$1=$1' will be FALSE if $1 is zero - so it won't print the line.

Try

 awk '$1=$1 {}1' ORS=' ' $page

EDIT: {}1 , not just 1 , sorry.

1 Like

why don't you just use

$ awk '1' ORS=' ' file

--edit---

if you use $ awk '$1=$1' file it will eat new line if any, and $1 = $1 1 suffix 1 to field 1

1 Like

Try...

echo -n "0 " > newfile

...instead.
Note the space...

EDIT:

As you were, ignore my stupidity.
Too many fingers not enough grey matter...

1 Like

You can add the leading 0, join the lines with a space, and still have a trailing newline (which makes the output valid text -- according to POSIX):

{ echo 0; cat file; } | paste -sd' ' -

Regards,
Alister

1 Like