Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed on Mac OS 10 to replace tab character in text files

I've been searching here for quite some time, and though I have found some really good info, nothing quite zeros in on my issue. Short-n-sweet, I'm using sed on Mac OS 10.11 to try and replace the tab character with the pipe character. All the info I have found on this so far, the syntax may work on other platforms but not on Mac OS 10.11. I know sed works on 10.11 as I can replace normal, standard characters all day long and even some punctuation like a comma. And yes, I have tried using \t. The sed string I found that works with standard characters is the following:

sed -i '' -e 's/,/|/g' /Users/username/Desktop/TABs2PIPE.txt

When I use \t in place of the , in the above string, it simply replaces all the lowercase t in the file.

So, any other Macheads out there who have gotten this to work I really would appreciate some help, thanks in advance.

like image 600
MacDudeDonny Avatar asked Oct 28 '16 18:10

MacDudeDonny


2 Answers

OSX sed is BSD-derived; this lineage of sed has never accepted \t as notation for the TAB character, IIRC. If your shell is bash (which is the default on OSX), try this instead:

sed -i '' -e $'s/\t/|/g' file_to_process.txt

$'...' is a bash extension; it's a '...' quoted word, but C-style backslash escapes are interpreted within. From the bash manpage:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

So, sed will see -e s/ /|/g where the gap between the first two spaces is a literal TAB character, and it should do the Right Thing with that.

If your shell is not bash, you can probably type a literal tab character yourself by typing control-V and then TAB.

like image 186
zwol Avatar answered Oct 12 '22 14:10

zwol


The way sed handles backslash-T is certainly unexpected if you haven't encountered it before!

This works:

sed -i s/\<CTRL-V><TAB>/\|/g text.txt

Where <CTRL-V> and <TAB> are the actual keys pressed.

like image 41
kurtrisser Avatar answered Oct 12 '22 14:10

kurtrisser