Yishu Fang
Yishu Fang

Reputation: 9958

How to use sed to delete leading digits?

I have a file:

$ cat file 
1 Fred
2 Fred3
3 Fred3
4 Fred3
5 Fred3
6 Fred3
7 Fred3
8 Fred3
9 Fred3
10 Fred3
11 Fred3
12 Fred288

I want to delete the leading numbers, the output should be like this:

$ cat file 
Fred
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred288

How can I achieve this goal using sed?

Upvotes: 4

Views: 8025

Answers (3)

Abdul Rehman Janjua
Abdul Rehman Janjua

Reputation: 1571

We can use sed to do this

sed -r 's/^[0-9]+//g' file

The sed -r tells we will be using regular expersion. We are tell sed to start from begining of line "^" and telling to look for digits "[0-9]+" in multiple form "//g" do it globally.

Upvotes: 3

Chris Seymour
Chris Seymour

Reputation: 85775

With sed:

sed 's/^[0-9]\+ //' file
Fred
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred3
Fred288

Do sed -i 's/^[0-9]\+ //' file to store the changes back to the file.


I would also recommend using cut for this

cut -d' ' -f2 file

Options:

-d, --delimiter=DELIM use DELIM instead of TAB for field delimiter

-f, --fields=LIST select only these fields; also print any line that contains no delimiter character, unless the -s option is specified

Upvotes: 9

P.P
P.P

Reputation: 121347

This will print the second word in each line:

awk '{print $2}' file

Upvotes: 4

Related Questions