amwalker
amwalker

Reputation: 355

How to replace multiple blank spaces with tab on a mac

I am trying to replace blank spaces with one tab in a fasta file, and then replace those tabs with new lines. It turns out that \t and \n do not work on mac terminal.

I have found that the \t is control+v tab, which is a major pain to type in the terminal and not conducive to copy/pasting scripts.

I have not been able to find a mac command equivalent to \n for a newline.

Desired outcome for replacing multiple blank spaces with tabs:

string1  string2
string1 <tab> string2

I have used

sed 's/  /control+v <tab>/g <filename

This works but is a pain because I need to know the exact number of consecutive blank spaces and I need to do the control+v tab deal.

For replacing each tab with a new line to get:

string1
string2

I have tried a similar method using control+v return, but that does not give the desired outcome.

Thanks in advance for you help.

Upvotes: 3

Views: 4233

Answers (3)

Mark Setchell
Mark Setchell

Reputation: 207445

Why replace multiple spaces with tabs and then replace tabs with newlines? Why not just replace multiple spaces with newlines? Or have I missed something?

Anyway, may I recommend tr to you? It transliterates, squeezes, or deletes characters. So, first usage is transliterate - change 'p' to 'd' and 't' to 'g'

echo pot | tr 'pt' 'dg'
dog

Second usage is squeeze repeated characters, via -s option:

echo moooooo | tr -s 'o'
mo

Final usage is delete characters, via -d:

echo "minced" | tr -d "nd"
mice

So, coming to your question, you want to squeeze spaces and replace with linefeeds

tr -s ' ' < fastfile | tr ' ' '\n'

Upvotes: 1

SLePort
SLePort

Reputation: 15461

To match multiple spaces :

echo "string string" | sed -e 's/  */$'\t'/g'

NB : Double the space to match one or more spaces.

To add newlines on OS X :

echo "string string" | sed -e 's/  */\'$'\n/g'

The $'\t' and $'\n' are respectively for a literal tab character and new line.

Upvotes: 2

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

You can do like this:

cat File
string              string

To replace consecutive space with single tab:

sed -r 's/ +/\t/g' File
string  string

To replace tab with newline, use sed 's/\t/\n/g':

sed -r 's/ +/\t/g' File | sed 's/\t/\n/g'
string
string

Upvotes: 1

Related Questions