How to remove trailing whitespaces with sed?

后端 未结 10 847
我在风中等你
我在风中等你 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条回答
  • 2020-11-28 22:14

    Thanks to codaddict for suggesting the -i option.

    The following command solves the problem on Snow Leopard

    sed -i '' -e's/[ \t]*$//' "$1"
    
    0 讨论(0)
  • 2020-11-28 22:18

    At least on Mountain Lion, Viktor's answer will also remove the character 't' when it is at the end of a line. The following fixes that issue:

    sed -i '' -e's/[[:space:]]*$//' "$1"
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-28 22:20

    To only strip whitespaces (in my case spaces and tabs) from lines with at least one non-whitespace character (this way empty indented lines are not touched):

    sed -i -r 's/([^ \t]+)[ \t]+$/\1/' "$file"
    
    0 讨论(0)
提交回复
热议问题