user3016814
user3016814

Reputation: 145

Exclude one string from bash output

I'm working now on a project. In this project for some reasons I need to exclude first string from the output (or file) that matches the pattern. The difficulty is in that I need to exclude just one string, just first string from the stream. For example, if I have:

1 abc
2 qwerty
3 open
4 abc
5 talk

After some script working I should have this:

2 qwerty
3 open
4 abc
5 talk

NOTE: I don't know anything about digits before words, so I can't filter the output using knowledge about them.

I've written small script with grep, but it cuts out every string, that matches the pattern:

'some program' | grep -v "abc"

Read info about awk, sed, etc. but didn't understand if I can solve my problem. Anything helps, Thank you.

Upvotes: 6

Views: 12842

Answers (6)

Barmar
Barmar

Reputation: 780724

Use the tail command to start at line 2 of the data:

tail -n +2 filename

or

command | tail -n +2

Upvotes: 0

fedorqui
fedorqui

Reputation: 289505

You can also use a list of commands { list; } to read the first line and print the rest:

command | { read first_line; cat -; }

Simple example:

$ cat file
1 abc
2 qwerty
3 open
4 abc
5 talk
$ cat file | { read first_line; cat -; }
2 qwerty
3 open
4 abc
5 talk

Upvotes: 0

Claes Wikner
Claes Wikner

Reputation: 1517

awk '!/1/' file
2 qwerty
3 open
4 abc
5 talk

Thats all!

Upvotes: 1

owais
owais

Reputation: 4922

give line numbers using sed which you want to delete

sed 1,2d

instead of 1 2 use line numbers that you want to delete

otherwise you can use

sed '/pattrent to match/d'

here we can have

sed '0,/abc/{//d;}'

Upvotes: 1

janos
janos

Reputation: 124648

Using awk:

some program | awk '{ if (/abc/ && !seen) { seen = 1 } else print }'

Alternatively, using only filters:

some program | awk '!/abc/ || seen { print } /abc/ && !seen { seen = 1 }'

Upvotes: 7

kenorb
kenorb

Reputation: 166339

You can use Ex editor. For example to remove the first pattern from the file:

ex +"/abc/d" -scwq file.txt

From the input (replace cat with your program):

ex +"/abc/d" +%p -scq! <(cat file.txt)

You can also read from stdin by replacing cat with /dev/stdin.

Explanation:

  • +cmd - execute Ex/Vim command
  • /pattern/d - find the pattern and delete,
  • %p - print the current buffer
  • -s - silent mode
  • -cq! - execute quite without saving (!)
  • <(cmd) - shell process substitution

Upvotes: 2

Related Questions