Shell Removing Tabs/Spaces

前端 未结 6 1562
醉酒成梦
醉酒成梦 2021-02-20 18:45

I\'ve used a grep command with sed and cut filters that basically turns my output to something similar to this

    this line 1


    this line 2


    another li         


        
相关标签:
6条回答
  • 2021-02-20 18:53

    You can also use grep:

    ... | grep -o '[^$(printf '\t') ].*' 
    

    Here we print lines that have at least one character that isn't white space. By using the "-o" flag, we print only the match, and we force the match to start on a non white space character.

    EDIT: Changed command so it can remove the leading white space characters.

    Hope this helps =)

    0 讨论(0)
  • 2021-02-20 18:56

    This can be done with the tr command as well. Like so

    | tr -s [:space:]

    or alternatively

    | tr -s \\n

    if you want to remove the line breaks only, without the space chars in the beginning of each line.

    0 讨论(0)
  • 2021-02-20 18:58

    I would do this, short and simple:

    sed 's: ::g'
    

    Add this at the end of your command, and all whitespace will go poof. For example try this command:

    cat /proc/meminfo | sed 's: ::g'
    
    0 讨论(0)
  • 2021-02-20 19:05

    Use grep "^." filename to remove blank lines while printing.Here,the lines starting with any character is matched so that the blank lines are left out. ^ indicates start of the line. . checks for any character.

    0 讨论(0)
  • 2021-02-20 19:09
    (whateverproducesthisoutput)|sed -E 's/^[[:space:]]+//'|grep -v '^$'
    

    (depending on your sed, you can replace [[:space:]] with \s).

    0 讨论(0)
  • 2021-02-20 19:11

    Add this filter to remove whitespace from the beginning of the line and remove blank lines, notice that it uses two sed commands, one to remove leading whitespace and another to delete lines with no content

    | sed -e 's/^\s*//' -e '/^$/d' 
    

    There is an example in the Wikipedia article for sed which uses the d command to delete lines that are either blank or only contain spaces, my solution uses the escape sequence \s to match any whitespace character (space, tab, and so on), here is the Wikipedia example:

    sed -e '/^ *$/d' inputFileName 
    
    • The caret (^) matches the beginning of the line.
    • The dollar sign ($) matches the end of the line.
    • The asterisk (*) matches zero or more occurrences of the previous character.
    0 讨论(0)
提交回复
热议问题