简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM