How to overwrite with a pipe in unix

1

So I am attempting to overwrite using a pipe:

    //reads contents of file| turns lowercase to uppercase | changes $ to # |
    // then attempts to overwrite original file with new version
    cat cutTester.txt|tr '[a-z]' '[A-Z]'|tr '$' '#' >cutTester.txt

but when I do this it just wipes the file. This is the contents of the file

    $first$second$third$fourth
    $fifth$sixth$seventh$eighth
    $ninth$tenth$eleventh$twelveth
    $thirteenth$fourthteenth$fifthteenth$sixthteenth
    $seventeenth$eightteenth$nineteenth$twenty
    $twenty-one$twenty-two$twenty-three$twenty-four

bordenE

Posted 2017-04-15T02:09:26.593

Reputation: 11

1

See Warning regarding ‘‘>’’.

– Scott – 2017-04-15T02:22:52.113

Answers

0

What is happening is that you are truncating cutTester.txt by using the ">" redirect notation. You are then processing your tr commands on the redirected output of an empty input file.

Note that the following also truncates the file:

$ cat cutTester.txt > cutTester.txt

Particularly if you are a developer, you may be used to writing statements like x=`eval $x + 1`, in which the eval expression is evaluated before the assignment. The behavior of redirection operators is not analogous, however. Consider that the implementation of redirecting a file's output back to itself would more than likely require the shell to create temp files behind the scenes and would not be as straightforward or efficient an operation as simply reassigning a variable (which only exists in memory).

Fortunately, it is simple enough to explicitly create a temporary file yourself:

#!/bin/bash

# reads contents of file| turns lowercase to uppercase | changes $ to # |
# then attempts to override original file with new version

cat cutTester.txt | tr '[a-z]' '[A-Z]' | tr '$' '#' > cutTester.tmp; mv cutTester.tmp cutTester.txt

Andrew Palmer

Posted 2017-04-15T02:09:26.593

Reputation: 129

You probably want to replace the ; with a && so that you don't lose your original file if the command fails or is aborted. Also, the cat command is just wasting time doing an extra copy. Simply redirect tr's input, tr <cutTester.txt ... – spectras – 2017-04-24T12:48:34.807