简体   繁体   English

如何使用 vi 删除文本文件中每行的前 5 个字符?

[英]How do I remove first 5 characters in each line in a text file using vi?

How do I remove the first 5 characters in each line in a text file?如何删除文本文件中每行的前 5 个字符?
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.我想删除 txt 文件中每行开头的数字和空格。

:%s/^.\\{0,5\\}// should do the trick. :%s/^.\\{0,5\\}//应该可以解决问题。 It also handles cases where there are less than 5 characters.它还处理少于 5 个字符的情况。

Use the regular expression ^..... to match the first 5 characters of each line.使用正则表达式^.....匹配每行的前 5 个字符。 use it in a global substitution:在全局替换中使用它:

:%s/^.....//

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只需将光标移至左上角位置 (gg),然后:CTRL+vGwlx

Since the text looks like it's columnar data, awk would usually be helpful.由于文本看起来像是柱状数据,awk 通常会有所帮助。 I'd use V to select the lines, then hit :!我会使用V来选择行,然后点击:! and use awk:并使用 awk:

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

to print out the second column of the data.打印出数据的第二列。 Saves you from counting spaces altogether.使您完全无需计算空间。

I think easiest way is to use cut.我认为最简单的方法是使用 cut。

just type cut -c n- <filename>只需输入cut -c n- <filename>

Try尝试

:s/^.....//

You probably don't need the "^" (start of line), and there'd be shortcuts for the 5 characters - but simple is good :)您可能不需要“^”(行首),并且有 5 个字符的快捷方式 - 但简单就是好的 :)

:%s/^.\\{0,5\\}//g用于全局,因为我们要为每一行删除每行的前 5 列。

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.就我而言,要删除每行的前2字符,我使用了这个:%s/^.\\{0,2\\}//并且无论是否使用g都一样。

I am on a VIM - Vi IMproved 8.2 , macOS version , Normal version without GUI.我使用的是VIM - Vi IMproved 8.2macOS versionNormal version without GUI.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM