Search code examples
perlreplacepunctuation

Find and replace punctuation character in first column for multiple text files


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?


Solution

  • 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.