1

Assume that the file ft has 25 lines of text. Explain the command:

tail -15 ft | tr "a" "A" > ft

and tell me how many lines the file ft has after the execution of the command.

I understand that tail -15 ft will grab the last 15 lines from the ft file and that tr 'a' 'A' will change any a into A.

But I don't understand why > tr deletes everything from the file.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

3 Answers3

2

What happens is that fist the shell sets up redirections (in this case, > ft), and that truncates ft and opens it for writing; then it sets up the rest of the pipeline. tail -15 ft gets an empty file and gives an empty result, which tr handles to replace nothing. ft is an empty file as a result.

vonbrand
  • 18,253
1

You're using a standard output redirection and not appending redirected output If you're trying to append the output to your original file, what I don't think so.

From man bash

Redirecting Output If the file does not exist it is created; if it does exist it is truncated to zero size.

Appending Redirected Output Redirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending on file descriptor n, or the standard output (file descrip‐ tor 1) if n is not specified. If the file does not exist it is created.

So, as you're specifying to redirect the output to the same file, this will be truncated and created with the expected output

What I suggest to do is to use sed with the redirection

$ tail -15 ft | sed -e 's|a|A|g' > sed_output
tachomi
  • 7,592
-1

You're not using the correct bash notation.

In bash, you have to use '>file' to overwrite a file and '>>file' to append to it. Instead, use '>>ft'.