0

I have a file test.txt, below the content:

SCDE1
SF9
STR1D2
SREDF21
FRED
STER2R4

I want to remove only the last character if it's a digit, so the output should be as below:

SCDE
SF
STR1D
SREDF2
FRED
STER2R
  • 2
    What have you tried so far and what is not working? – kemotep Dec 5 '18 at 2:42
3

Does this match your criteria?

Input data:

cat user324294
SCDE1
SF9
STR1D2
SREDF21
FRED
STER2R4

And transformation:

sed 's/[0-9]$//' user324294 
SCDE
SF
STR1D
SREDF2
FRED
STER2R

Explanation of the regex: any digit followed by a line end gets replaced with nothing.

0

This removes the last character if it is a number.

sed 's|[0-9]$| |g' file

Output:

SCDE
SF
STR1D
SREDF2
FRED
STER2R
  • 1
    That trailing whitespace! 😬 – Sparhawk Dec 5 '18 at 5:57
  • g is useless here – αғsнιη Apr 22 at 10:00
0

What you need is a regex (Regular Expression) to match your text.
The regex that match one number is [0-9]. The end of the line is $.
Both together:

 [0-9]$

Now, we can use sed to remove the text on each line:

 sed 's/[0-9]$//' test.txt

If you need to replace several digits, use a repetition modifier, probably * in this case. Not what you are asking but useful to know:

 sed 's/[0-9]*$//' test.txt

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.