Lukas Svagr
Lukas Svagr

Reputation: 15

How can I delete one row in BASH?

I have this code:

1441149726 jezevec Lukas
1441173967 tesak Petr
1441174056 kuna Marek
1441174063 myval Lukas
14411728 potter Marek
1441175214 hermiona Marek
1441219281 liska Marek
1441219282 liska Marek
1441219282 liska Marek
1441219283 liska Marek

How Can I delete first record with liska on 7th line? Maybe with sed? I have it in a file.

Upvotes: 0

Views: 98

Answers (2)

Cyrus
Cyrus

Reputation: 88766

With GNU sed:

sed '0,/liska/{/liska/d}' file

Output:

1441149726 jezevec Lukas
1441173967 tesak Petr
1441174056 kuna Marek
1441174063 myval Lukas
14411728 potter Marek
1441175214 hermiona Marek
1441219282 liska Marek
1441219282 liska Marek
1441219283 liska Marek

Upvotes: 3

Charles Duffy
Charles Duffy

Reputation: 295650

A short awk script is one approach that offers substantial control:

awk '
BEGIN { seen=0; }
{
  if(seen == 0 && $2 == "liska") {
    seen=1
  } else {
    print $0
  }
}
' <infile >outfile

That said, you could literally implement this in native bash, too, if you wanted:

#!/bin/bash

seen=0
while IFS= read -r line; do
  if ((seen == 0)) && [[ $line = *" liska *" ]]; then
    seen=1
  else
    printf '%s\n' "$line"
  fi
done <in.txt >out.txt
mv out.txt in.txt # if you want to replace the input file

Upvotes: 1

Related Questions