1

We create the following Perl one liner. In order to delete double lines except the first match line, the second part of the syntax is to ignore the lines with remark "#".

Example:

# more /tmp/test

     # abra_kadabra

abra_kadabra
abra_kadabra


# perl -i -ne -e'next if /^#/; next if /abra_kadabra/ && ++$ok > 1; print' /tmp/test


# more /tmp/test

     # abra_kadabra

In fact the Perl syntax is not ignoring the remarked lines in spite we set the next if /^#/1:

Please advice what is wrong in my syntax?

Expected output

# more /tmp/test

     # abra_kadabra

abra_kadabra

Other examples:

# more /tmp/test

     # abra_kadabra
#       abra_kadabra
abra_kadabra 1
abra_kadabra 2
abra_kadabra 3
abra_kadabra 4

Expected output:

# more /tmp/test

     # abra_kadabra
#       abra_kadabra
abra_kadabra 1

closed as off-topic by Rui F Ribeiro, Isaac, n.st, thrig, Sparhawk Aug 21 '18 at 6:20

  • This question does not appear to be about Unix or Linux within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

2

next if /^#/; ...; print means the lines that start with # will not be printed.

Here, you want

perl -i -ne 'next if !/^\s*#/ && /abra_kadabra/ && $count++; print' /tmp/test

That is you want not to call next for the commented-out lines if you want to preserve them.

Same with sed for those implementations that support -i (-i '' with FreeBSD and derivatives):

sed -i -e '/^[[:space:]]*#/b' -e '/abra_kadabra/!b' -e 'x;/./d;g' /tmp/test

Where we use the hold space to remember if we've already seen abra_kadabra before.

  • yes I test it and seems its work ( +1 ) – yael Aug 20 '18 at 12:32
0

You have anchored the # to match only at the beginning of a line. If you want to skip all lines that begin with '#', even after leading whitespace, you need:

next if /^\s*#/

This will skip lines with optional, leading whitespace followed by a #.

  • I see another problem that all lines with mark are deleted also , can we fix that? see please example of expected output – yael Aug 20 '18 at 12:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.