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
1

1 Answer 1

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
1
  • 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
    Apr 24, 2017 at 12:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .