user1709294
user1709294

Reputation: 1805

Shell Removing Tabs/Spaces

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

Upvotes: 12

Views: 60426

Answers (7)

Jay Brunet
Jay Brunet

Reputation: 3750

Remove spaces and tabs:

echo $'spaces    tabs\ttabs' | tr -d '\t '

Output: spacestabstabs

Remove tabs only:

echo $'spaces    tabs\ttabs' | tr -d '\t'

Output: spaces tabstabs

Remove spaces only:

echo $'spaces    tabs\ttabs' | tr -d ' '

Output: spacestabs tabs

Upvotes: 0

Cestarian
Cestarian

Reputation: 251

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'

Upvotes: 7

Karthick Balaji
Karthick Balaji

Reputation: 64

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.

Upvotes: 2

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

Upvotes: 4

amdn
amdn

Reputation: 11582

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.

Upvotes: 12

asenovm
asenovm

Reputation: 6517

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.

Upvotes: 11

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143249

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

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

Upvotes: 0

Related Questions