alnet
alnet

Reputation: 1233

how to delete two lines that starts with same character in sed?

I have a text file. In case there are more than one consecutive line that starts with @, I want to delete all these lines, except of the last occurrence of of a line with @.

For example, lets say I have input file:

abc

@abc

@def

333

@asd

@poi

@789

The output should be:

abc

@def

333

@789

Upvotes: 0

Views: 978

Answers (4)

Kent
Kent

Reputation: 195109

I saw awk tag. so I add an awk one-liner, which could sovle your problem: (see test below)

kent$  cat a.txt
abc
@abc
@def
333
@asd
@poi
@789

kent$  awk 'BEGIN{FS=""}
        {if(c==$1){l=$0;next;} if(c) print l;c=$1;l=$0;} 
        END{print }' a.txt 
abc
@def
333
@789

Upvotes: 1

Thor
Thor

Reputation: 47109

A multi-line sed solution:

sed -n '
  $p         # Always print last line
  N          # Append next line to pattern space
  /@.*\n@/D  # Delete first line of pattern space if both
             # lines start with an @, and start over
  P          # Otherwise print first line of pattern space,
  D          # delete it and start over
  ' infile

Upvotes: 1

OpenSauce
OpenSauce

Reputation: 8623

http://ideone.com/Ng7p2

/^@/ { last_line=$0; line_to_print=true }
/^[^@]/ { if ( line_to_print == true ) print last_line; print $0; line_to_print=false }
END { if ( line_to_print == true ) print last_line }

Upvotes: 0

Kasapo
Kasapo

Reputation: 5374

You can use tr with sed:

cat input_file | tr '\n' ' ' | sed s/<pattern>//

tr replaces newlines with spaces, making the regex easier.

This pattern seems to work:

cat file.txt | tr '\n' ' ' | sed -e "s/\(@\w*\s\)*\(@\w*\s\)/\2/g"

Upvotes: 2

Related Questions