0

I have a text file and manage to find the line through output comparison. With the book title and author name.

awk -F ':' '/KungFu Feet|Chuck Norris/'  test.txt

Kungfu Feet:Chuck Norris:12:1:1

Is there any way to delete the line using awk and return the output in a bash file?

EDIT

I would like to do a check for the following item before i do the deleting using awk

  If (( Book = KungFu Feet  && Author = Chuck Norris )); do
    echo "Item is found unable to delete" 
  else 
    echo "Deleting.."  

2 Answers 2

2

Something like this will do what you want:

$ awk -F ':' '!/KungFu Feet|Chuck Norris/'  test.txt | tee newtest.txt
KungFa Feet|Chuck Narris:12:1:1
KungFe Feet|Chuck Nerris:12:1:1

New file

$ cat newtest.txt 
KungFa Feet|Chuck Narris:12:1:1
KungFe Feet|Chuck Nerris:12:1:1
6
  • Thanks alot. but i would like to output a if else statement with echo so "if ( $Book = "KungFu Feet" && $Author = "Chuck Norris" ) echo Item found deleting using awk else Item not found.
    – Len
    Jan 27, 2014 at 17:21
  • 1
    @LennonChia - can I ask why? Not being wise, I'm generally curious as to why you want that over what I posted. I'm wondering if there is more to your ultimate goals with your question too.
    – slm
    Jan 27, 2014 at 17:25
  • it work thanks alot for being so helpful but i would like to do a check on my shell script before i do the awk delete. so when the user enter the book and the author there will be a check before i do a awk delete. I am still stuck trying to figure out how to do it using bash. But i am hoping to learn to use awk too. I am sorry if i may be giving the wrong impression i am still trying to learn some of the bash basic , awk and sed function.
    – Len
    Jan 27, 2014 at 17:28
  • @LennonChia - my example doesn't do a awk delete, just creates a 2nd file.
    – slm
    Jan 27, 2014 at 17:31
  • i can rename the file so it alright and delete the old file :)
    – Len
    Jan 27, 2014 at 17:39
1

Unless you have a need to do this with awk, you might want to try something with grep and sed:

if grep -E "(KungFu Feet|Chuck Norris)" your_file ; then
    # fancy stuff in case string has been matched
    sed -r "/(KungFu Feet|Chuck Norris)/d" < your_file > new_file
else
    # fancy stuff in case it hasn't
fi

If you need POSIX sed compatibility, you'll have to expand the regex for sed (grep in recent POSIX versions supports the -E option):

sed -r "/KungFu Feet/d;/Chuck Norris/d" < your_file > new_file

Some version of sed also allow in-place changes through the -i option.

Re-reading the answer, you would probably need to match just "KungFu Feet:Chuck Norris" in both sed and grep. This is of course thanks to the extremely simple format of your data.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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