Tr command can't pipe output?

I have a file.txt file that has these entries

Ny

LA

SF

I ran the command tr '\ n' ',' <file.txt and successfully removed all newlines.

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

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

but it doesn't put anything in the .txt file and the resulting file is empty. Can anyone explain to me why tr output is lost due to redirection.

+3


source to share


3 answers


because it first opens the output file which deletes what is in the file and then feels nothing in the tr command and returns to an empty file

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

      



will work

+5


source


since you tagged your question with sed

i suggest sed oneliner, also sed can modify your file "in place" with the "-i" option

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 option, you need:

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

      

0


source


If you just want to replace the newline ,

you can us this

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

0


source







All Articles