0

Need a solution similar to this post (Find and replace a particular term in multiple files) but for a punctuation character replacement in the first column of each delimited tab text file.

Example:

file1.txt
afile2.txt
3file.txt
...

all other file names end with .txt

Format of txt files has a "tab" in between column and look like:

aaaa:bbb    second_column    third_column
w:xyz    another_second_column    another_third_column

I need to replace the : in the first column to another character such as ##.

Please help.

Does perl treat the : character as a column cutter?

Community
  • 1
  • 1
horkust
  • 15
  • 3
  • 1
    Based on your comments, I get the feeling that you are asking [The Wrong Question](http://english.stackexchange.com/q/45154/13917). Why do you want to remove the colon? It is not a meta character in perl. – TLP Oct 28 '11 at 14:10

1 Answers1

3

Replace inplace the first colon in the first tab-delimited column in a line by ##:

perl -i.bak -pe's/^([^\t:]*):/$1##/' *.txt

It processes all .txt-files in the current directory saving backup versions to .bak-files.

Here's a variant that doesn't require the capture (suggested by @Brad Gilbert in the comments):

perl -i.bak -pe's/^[^\t:]*\K:/##/' *.txt

Both scripts produce the same result.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 1
    `s/:/##/` would be enough. However +1. – Toto Oct 28 '11 at 13:29
  • I get the first column chopped off whenever there is a ":" character. That's why I need the replacement. What does ":" do in perl? Yes, the ^\t will leave the 2nd and 3rd column untouched. – horkust Oct 28 '11 at 13:31
  • @M42: It the first column doesn't have `:` then `s/:/##/` is wrong. – jfs Oct 28 '11 at 13:35
  • @horkust: Construct a minimal example that demonstrates your problem (with the smallest input, your code that processes it, expected output, and what you get instead) and [post it as a question](http://stackoverflow.com/questions/ask). – jfs Oct 28 '11 at 13:38
  • `perl -i.bak -pe's/^[^\t:]*\K:/##/' *.txt` works on newer versions of Perl – Brad Gilbert Oct 28 '11 at 17:22