How to remove trailing whitespaces with sed?

后端 未结 10 890
我在风中等你
我在风中等你 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:02

    I have a script in my .bashrc that works under OSX and Linux (bash only !)

    function trim_trailing_space() {
      if [[ $# -eq 0 ]]; then
        echo "$FUNCNAME will trim (in place) trailing spaces in the given file (remove unwanted spaces at end of lines)"
        echo "Usage :"
        echo "$FUNCNAME file"
        return
      fi
      local file=$1
      unamestr=$(uname)
      if [[ $unamestr == 'Darwin' ]]; then
        #specific case for Mac OSX
        sed -E -i ''  's/[[:space:]]*$//' $file
      else
        sed -i  's/[[:space:]]*$//' $file
      fi
    }
    

    to which I add:

    SRC_FILES_EXTENSIONS="js|ts|cpp|c|h|hpp|php|py|sh|cs|sql|json|ini|xml|conf"
    
    function find_source_files() {
      if [[ $# -eq 0 ]]; then
        echo "$FUNCNAME will list sources files (having extensions $SRC_FILES_EXTENSIONS)"
        echo "Usage :"
        echo "$FUNCNAME folder"
        return
      fi
      local folder=$1
    
      unamestr=$(uname)
      if [[ $unamestr == 'Darwin' ]]; then
        #specific case for Mac OSX
        find -E $folder -iregex '.*\.('$SRC_FILES_EXTENSIONS')'
      else
        #Rhahhh, lovely
        local extensions_escaped=$(echo $SRC_FILES_EXTENSIONS | sed s/\|/\\\\\|/g)
        #echo "extensions_escaped:$extensions_escaped"
        find $folder -iregex '.*\.\('$extensions_escaped'\)$'
      fi
    }
    
    function trim_trailing_space_all_source_files() {
      for f in $(find_source_files .); do trim_trailing_space $f;done
    }
    

提交回复
热议问题