3

I have a file with a list of values that end with a letter. Is there an easy way to add a space or tab before the last character of each line to separate the number from the letter?

44A  
354T  
1453C  
77D

So that the output looks like this:

44 A  
354 T  
1453 C  
77 D
0

4 Answers 4

6

If you never have any white space after the last character and before the end of the line, use:

sed 's/.$/ &/' file

or

perl -pe 's/.$/ $&/' file

If you can have whitespace before the end of the line, use this instead:

perl -pe 's/(.*)(\S)/$1 $2/' file
1
  • Nice. Also s/(?=\S\s+$)/ / but I don't think that gains anything over your sol'n Commented Oct 7, 2015 at 19:47
4

This works for the stated case:

sed 's/\(.\)$/\ \1/' file.txt 

It will break down if you want a space anywhere else.

0
1

if lines are not empty...

perl -pe 'substr($_,-2,0)=" "'
0

In vi, you can do it with:

:%s/\(.\)$/ \1/

Broken down, this is:

:%s    #Apply substitution to all lines
   /\(.\)$    #Search for a single character followed by the end of the line
          / \1/    #Replace with a space followed by that character

This does assume you don't have any whitespace at the end of your lines. If that's not always the case, use:

:%s/\(\S\)\s*$/ \1/

This will strip off any trailing whitespace and add a single space before the last remaining character on each line.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .