6

I have a file that contains a bunch of lines.
I would like to remove entries from file which starts with nnn and are longer than 25 characters.

For now I am able only to make two separates sed:

sed '/^nnn/d' input.txt > output.txt
sed '/^.\{25\}./d' input.txt > output.txt

but this is not my goal.

Example input:

nnnASDDGfdgdsfndsjfndsjfdfgGHGHGhfhfd
nnnASDDGfdgdsfn
sadbSADSDDFSDFrrrRRRRRRRttTGGGG

Desired output:

nnnASDDGfdgdsfn
sadbSADSDDFSDFrrrRRRRRRRttTGGGG
0
6

sed solution:

sed -E '/^nnn.{23}/d' file
  • /^nnn.{23,}/ - match only line that starts with nnn and has more than 25 characters (.{23,} - match character sequence of at least 23 characters long)
  • d - delete the matched line

The output:

nnnASDDGfdgdsfn
sadbSADSDDFSDFrrrRRRRRRRttTGGGG

The same with awk command:

awk '!/^nnn.{23}/' file
2
  • Thanks it works but T had to sligtly change to: /^.\{26,\}/d – user3626411 Mar 6 '18 at 12:03
  • 3
    You don't need two conditions: sed -E '/^nnn.{23}/d' infile will do. – don_crissti Mar 6 '18 at 12:07
8

This is best done by awk:

awk '/^nnn/ && length >= 25 { next } { print }' file

The /^nnn/ will match the given regular expression ("line starts with nnn"). length (or length($0)) will return the length of the input line. If the expression matches and the length is 25 or longer, the line is ignored, otherwise it's printed. The { print } may be replaced by just 1 if it feels too long to type.

Or,

awk '!/^nnn/ || length < 25' file

This does the same thing but with the inverse condition. If the line does not match the expression, or if it's less than 25 characters, then it's printed. Other lines are ignored.

Both of these produce

nnnASDDGfdgdsfn
sadbSADSDDFSDFrrrRRRRRRRttTGGGG

for the given input data.

0
6

You can do it like:

sed -e '/^nnn/!b' -e '/.\{26\}/d'

Or:

sed '/^nnn/{/.\{26\}/d;}'
2

How about humble grep

$ grep -v '^nnn.\{23\}' ip.txt
nnnASDDGfdgdsfn
sadbSADSDDFSDFrrrRRRRRRRttTGGGG

$ # if ERE is available
$ grep -vE '^nnn.{23}' ip.txt
nnnASDDGfdgdsfn
sadbSADSDDFSDFrrrRRRRRRRttTGGGG

-v, --invert-match Invert the sense of matching, to select non-matching lines.

2

With grep

grep -v '^nnn.\{23\}' infile

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.