1

I have multiple files ( > 1000) with same name in different subdirectories

dir1/out.txt

   # white row
    1 2 3 4 5
    3 3 4 5 6 
    4 1 4 5 8
    # white row

dir2/out.txt

 # white row  
    1 2 3 4 5
    3 3 4 5 6 

    4 1 4 5 8
    # white row 

dir3/out.txt

# white row 
1 2 3 4 5
3 3 4 5 6 
4 1 4 5 8
# white row 

I want to remove all white spaces (usually at heading row, tail row and in between rows.

Is there is quick way to do in Unix ? Apolozie for simple question.

Edit:

I am not trying to remove every space rather just whole lines that are white spaces

4

2 回答 2

1

To remove just blank lines, use

sed -i '/^$/d' file

To remove blank-lines containing spaces use

sed -i '/^[[:blank:]]*/$' file

To remove all spaces from file, use

sed 's/ //g' file > file.new && /bin/mv file.new file

Thats a space char, if the white space might include tab char, then use

sed 's/[[:blank:]]//g' file

If you're using GNU sed on a linux, then you can do

sed -i 's/[[:blank:]]//g' file

And if you want to delete blank lines, then add

 sed -i 's/[[:blank:]]//g;/^$/d' file

You'd wrap all of this in a find cmd to get your file names like

 cd $baseDir ; find . -name '*.txt' -print | xargs sed -i 's/[[:blank:]]//g;/^$/d' {}

Use just the first part,

 find . -name '*.txt' -print 

And adjust until you see the correct filename list appearing.

Then test the 2nd half, by forcing the find output to have just 1 test filename as output, i.e.

 find . -name 'myTestOut.txt' | xargs ...

I don't have an easy way to test this now, but this sort of question gets asked every day here on S.O., search by [unix] [linux] [xargs] [sed] .

I hope this helps.

于 2012-05-21T16:43:14.517 回答
1

This will find all the files named out.txt in subdirectories of present working directory and deletes while-space containing lines from each file.

find . -name "out.txt" -exec sed -i '/^$/d' '{}' \;

Note: You must own write permissions to modify these files.

于 2012-05-21T17:04:21.483 回答