Write over data to new file

hi..i would ask about how to write over data to new file with BASH.
so..assume my data looks like this :
11
12
13
14
15
...and so on. It's always line by line. and that's for the first file.
i want to write over those numbers into second file but by using space. so my second file should be look like this :
11 12 13 14 15...and so on

i tried with :

echo $dataFromFirstFile > $2

which $2 is second argument for my second file.
but, i dont get what i want.. :confused:
thanks before! :slight_smile:

Try:

(tr "\n" " " < input; echo) > output

Solution given by bartus11 is best option to use here, but if you are interested to know how to achieve this using echo, use \c option which will suppress trailing newline:-

#!/bin/bash
while read line
do
        echo -e "${line} \c" >> newfile
done < oldfile
echo -e "\n" >> newfile # put final newline

OR use sed:-

sed ':a;N;$!ba;s/\n/ /g' oldfile > newfile

what if this 'input' isn't a file?
i have couple of numbers which is a result of a 'for loop'. assume that it looks like this :

for varN in 1 2 3 4; do echo $varN; done;

the result will be :
1
2
3
4

and those numbers will be saved as $varN.

so..how can i put this varN into a new file which is separated by space?

for varN in 1 2 3 4; do echo -n "$varN "; done > output
echo >> output
1 Like

I got it! Thanks a lot