Ray Salemi
Ray Salemi

Reputation: 5933

Why does `git stripspace` delete all text?

I'm trying to run git stripspace but the documentation is not helpfull.

It appears that git stripspaces takes stdin as its input and writes to stdout but:

% git stripspace < myfile.txt > myfile.txt

deleted all the text in myfile.txt

I wish the documentation provided an invocation example. Does anyone have one?

Upvotes: 0

Views: 1102

Answers (2)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391596

The problem here is that you're redirecting from and to the same file. It wasn't GIT that did it. When you redirect stdout to a file, it first creates that file. Which in your case, created it empty (in other words, it overwrote your file).

Try changing your simple command, which is this:

git stripspace < myfile.txt > myfile.txt

to this:

git stripspace < myfile.txt > my-other-file.txt

and it should work just fine.

Upvotes: 4

Michael Burr
Michael Burr

Reputation: 340406

sponge is the tool to solve exactly this problem. It first "soaks up" all of the data piped into it then writes it out to the specified file. It's part of the moreutils package - on Ubuntu install it with sudo apt install moreutils,

Here's an example using a file spacetest.txt - the awk command is used to to help visualize the trailing spaces that exist in the file:

# print the file spacetest.txt with '%' appended to each line-end to show trailing spaces

~/temp/stripspace-test$ awk '{ print $0 "%" }' spacetest.txt 
%
%
line 1 has a space at the end %
line 2 has 2 spaces at the end  %
line 3 has 3 spaces at the end   %
%
the next line has 4 spaces%
    %
three blank lines follow this one%
%
%
%

# 'redirect' from and to spacetest.txt using `sponge` as a go-between

~/temp/stripspace-test$ git stripspace < spacetest.txt | sponge  spacetest.txt


# print the file spacetest.txt again to demonstrate everything is as expected

~/temp/stripspace-test$ awk '{ print $0 "%" }' spacetest.txt 
line 1 has a space at the end%
line 2 has 2 spaces at the end%
line 3 has 3 spaces at the end%
%
the next line has 4 spaces%
%
three blank lines follow this one%

Upvotes: 4

Related Questions