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
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
  • Nice. Also s/(?=\S\s+$)/ / but I don't think that gains anything over your sol'n – glenn jackman Oct 7 '15 at 19:47
3

This works for the stated case:

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

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.