How do I remove first 5 characters in each line in a text file using vi?
Asked Answered
P

9

59

How do I remove the first 5 characters in each line in a text file?
I have a file like this:

   4 Alabama
   4 Alaska
   4 Arizona
   4 Arkansas
   4 California
  54 Can
   8 Carolina
   4 Colorado
   4 Connecticut
   8 Dakota
   4 Delaware
  97 Do
   4 Florida
   4 Hampshire
  47 Have
   4 Hawaii

I'd like to remove the number and the space at the beginning of each line in my txt file.

Papst answered 10/2, 2015 at 0:7 Comment(0)
T
110

:%s/^.\{0,5\}// should do the trick. It also handles cases where there are less than 5 characters.

Tiltyard answered 10/2, 2015 at 0:11 Comment(2)
Thanks, but I needed to add a g to make it work. :%s/^.\{0,5\}//gImago
Explanation of the macro?Johan
N
28

Use the regular expression ^..... to match the first 5 characters of each line. use it in a global substitution:

:%s/^.....//
Nucleo answered 10/2, 2015 at 0:12 Comment(1)
Actually Barmar meant a regexp match - it's what's getting substituted. ^ matches the beginning of the line and . matches any character. :s command substitutes the whole match between the first and second slash (in this case five, possibly different, characters at the beginning of the line) with what's between the last two slashes - nothing, effectively removing them.Tiltyard
L
13

As all lines are lined up, you don't need a substitution to solve this problem. Just bring the cursor to the top left position (gg), then: CTRL+vGwlx

Levo answered 1/9, 2017 at 5:34 Comment(0)
S
4

I think easiest way is to use cut.

just type cut -c n- <filename>

Settler answered 29/10, 2019 at 7:18 Comment(1)
It is specifically asked "using vi"Claudication
A
3

Try

:s/^.....//

You probably don't need the "^" (start of line), and there'd be shortcuts for the 5 characters - but simple is good :)

Abreast answered 10/2, 2015 at 0:12 Comment(2)
For this to work globally (on all lines), add % before s. That is, use :%s/^.....//Warm
Wow, can’t believe I missed that - thanks, Good catch.Abreast
G
2

Since the text looks like it's columnar data, awk would usually be helpful. I'd use V to select the lines, then hit :! and use awk:

:'<,'>! awk '{ print $2 }'

to print out the second column of the data. Saves you from counting spaces altogether.

Ghiselin answered 11/8, 2016 at 23:24 Comment(1)
It is specifically asked "using vi"Claudication
I
2

:%s/^.\{0,5\}//g for global, since we want to remove first 5 columns of each line for every line.

Inbreathe answered 8/2, 2019 at 22:2 Comment(0)
H
1

In my case, to Delete first 2 characters Each Line I used this :%s/^.\{0,2\}// and it works with or without g the same.

I am on a VIM - Vi IMproved 8.2, macOS version, Normal version without GUI.

Horton answered 30/10, 2021 at 4:20 Comment(0)
R
0

:%norm! 5x applies the built-in x key command five times on the start of all lines

Reiser answered 17/6, 2024 at 15:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.