-->

Shell Removing Tabs/Spaces

2020-08-17 06:36发布

问题:

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 line 3


    another line 4

I'm trying to get an output without the spaces in between the lines and in front of the lines so it'd look like

    this line 1
    this line 2
    another line 3
    another line 4

I'd like to add another | filter

回答1:

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.


回答2:

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.



回答3:

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'


回答4:

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 =)



回答5:

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.



回答6:

(whateverproducesthisoutput)|sed -E 's/^[[:space:]]+//'|grep -v '^$'

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



标签: grep