How to remove trailing whitespaces with sed?

后端 未结 10 904
我在风中等你
我在风中等你 2020-11-28 21:49

I have a simple shell script that removes trailing whitespace from a file. Is there any way to make this script more compact (without creating a temporary file)?

<         


        
10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 22:19

    For those who look for efficiency (many files to process, or huge files), using the + repetition operator instead of * makes the command more than twice faster.

    With GNU sed:

    sed -Ei 's/[ \t]+$//' "$1"
    sed -i 's/[ \t]\+$//' "$1"   # The same without extended regex
    

    I also quickly benchmarked something else: using [ \t] instead of [[:space:]] also significantly speeds up the process (GNU sed v4.4):

    sed -Ei 's/[ \t]+$//' "$1"
    
    real    0m0,335s
    user    0m0,133s
    sys 0m0,193s
    
    sed -Ei 's/[[:space:]]+$//' "$1"
    
    real    0m0,838s
    user    0m0,630s
    sys 0m0,207s
    
    sed -Ei 's/[ \t]*$//' "$1"
    
    real    0m0,882s
    user    0m0,657s
    sys 0m0,227s
    
    sed -Ei 's/[[:space:]]*$//' "$1"
    
    real    0m1,711s
    user    0m1,423s
    sys 0m0,283s
    

提交回复
热议问题