Sahil
Sahil

Reputation: 9478

tr command not able to direct the Output?

I have got a file file.txt witch has got these entries

NY

LA

SF

I ran the command tr '\n' ',' < file.txt and it successfully deleted all of the newline characters.

I need all of this output in the same file.txt file, so I redirected the output like this

tr '\n' ',' < file.txt > file.txt,

but It does not put anything in the file.txt and the resultant file is empty, Can anyone explain to me why the output of tr is getting lost due to redirection.

Upvotes: 5

Views: 8548

Answers (3)

Mirage
Mirage

Reputation: 31568

If you just want to replace the newline with , you can us this

awk 'ORS=","' temp.txt > file.txt

Upvotes: 0

Kent
Kent

Reputation: 195199

since you have tagged your question with sed, I suggest a sed oneliner, also sed could change your file "in-place" with option "-i"

sed -i ':a $!N; s/\n/,/; ta' file

or with awk

 

awk '{x=x""sprintf($0",")}END{gsub(/,$/,"",x);print x}' file

no like sed, awk has no "in-place" changing option, you have to :

awk '...' file > /tmp/mytmp && mv /tmp/mytmp file

Upvotes: 0

Vorsprung
Vorsprung

Reputation: 34377

because it opens the output file first which deletes what is in the file and then feels nothing into the tr command and back out into the empty file

tr '\n' ',' < file.txt > file2.txt 

will work

Upvotes: 6

Related Questions