2

I have a txt file under CentOS in which I want to replace any "\t\n" with "\t\t". I tried this:

sed -i -E 's/\t\n/\t\t/g' myfile.txt

but it doesn't work. I don't know if CentOS doesn't support regex in sed.

Any help is appreciated!

p.s.

Input(two lines):

1\t2\t3\t$ 4\t5\t6\t$

Output(one line): 1\t2\t\3\t\t4\t5\t6\t\t

In Editplus, the find regex is '\t\n' and the replace is '\t\t'. Then all lines ending with '\t\n' will become one line, and each '\n' is replaced by one additional '\t'.

p.s.

my file is read like this (cat -A myfile.txt)

enter image description here


Jonathan Zhou
  • 89
  • 1
  • 5

2 Answers2

0

You may use this perl command to join lines if previous line has a single tab:

perl -i -0777 -pe 's/(\S\t)\n(?!\z)/$1\t/g' excel.log

(?!\z) is a negative lookahead to fail this match for last line of the file.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/223884/discussion-between-jonathan-zhou-and-anubhava). – Jonathan Zhou Oct 30 '20 at 18:26
0

You need to escape the backslashes.

sed -i -E  's/\\t\\n/\\t\\t/g' myfile.txt
zdaee
  • 11
  • 1
  • Sorry this solution leaves the text file intact. – Jonathan Zhou Oct 30 '20 at 17:54
  • @JonathanZhou what version of sed do you have. I tried this out on CentOS 8 which has sed-4.5-1.el8.x86_64. – zdaee Oct 30 '20 at 18:12
  • I am using CentOS 8 too. But I don't know what sed version is. May you please tell me what command to tell the version? – Jonathan Zhou Oct 30 '20 at 18:23
  • Just saw your update, this is only replacing the literal characters. It won't work for what you're trying to do. – zdaee Oct 30 '20 at 18:33
  • In essence, there are multiple lines ending with \t\n. I would like to join the lines and replace \n with one additional \t. In Editplus, the find is '\t\n' and the replaced with '\t\t'. then it works fine in Editplus. – Jonathan Zhou Oct 30 '20 at 18:43
  • I mean my specific solution won't work for what you're trying to do. – zdaee Oct 30 '20 at 18:53
  • This might be what you're looking for. https://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed – zdaee Oct 30 '20 at 20:27