In Shell how do I delete long lines of text

  • 2020-06-15 11:01:15
  • OfStack

In Shell, how do I delete long lines of text

Sometimes need to perform delete delete files, which are frequently used at this time will use vi dd command in command, such as to perform first 10 G (jump to the line 10), and then execute 20 dd 20 rows (delete), but the reality is not necessarily so routine, for example, to delete files, a length of more than 200 characters in line, if the text is smaller, well, if it's tens of thousands of lines, a few 100000 line? It's not realistic to think about using vi. The solution I came up with, for example, was to use the sed,awk,egrep commands. Take a simple example.

If you say the following text file, delete any file that is longer than 5 characters.


root@linux# cat data 
1 
22 
333 
4444 
55555 
666666 
7777777 
88888888 

Method 1: The length() function using the awk command


root@linux# cat data | awk '{if (length($0) <=4 ) print $0}' 
1 
22 
333 
4444 

Method 2: Use the grep command


root@linux# cat data | egrep -w '^.{1,4}' 
1 
22 
333 
4444 

Method 3: Use the sed command


root@linux# cat data | sed -n '/^.\{5,\}/!w NewFile' 
root@linux# cat NewFile 
1 
22 
333 
4444 

Remark:

1. When using the awk,grep command, you can redirect the processed file to another new file
2. The egrep-ES42en parameter, which represents the word that matches only the pattern
3. ^. Represents a line that begins with any character. This matches the -w command
4.! w! For all pattern mismatches, w is output and written to the new file NewFile

If you have any questions, please leave a message or go to this site community exchange discussion, thank you for reading, hope to help you, thank you for your support to this site!


Related articles: