Dennis Vymer
Dennis Vymer

Reputation: 119

Bash, deleting specific row from file

I have a file with filename and path to the file I want to delete the the rows which have files that do not exist anymore

file.txt (For now all existing files):

file1;~/Documents/test/123
file2;~/Documents/test/456
file3;~/Test
file4;~/Files/678

Now if I delete any of the given files(file 2 AND file4 fore example) and run my script I want it to test if the file in the given row exists and remove the row if it does not

file.txt(after removing file2, file4):

file1;~/Documents/test/123
file3;~/Test

What I got so far(Not working at all): -Does not want to run at all

#!/bin/sh
  backup=`cat file.txt`
rm -f file.txt
  touch file.txt

  while read -r line
  do
    dir=`echo "$line" | awk -F';' '{print $2}'`
    file=`echo "$line" | awk -F';' '{print $1}'`

    if [ -f "$dir"/"$file" ];then
        echo "$line" >> file.txt
    fi
  done << "$backup"

Upvotes: 0

Views: 1095

Answers (2)

Ed Morton
Ed Morton

Reputation: 203229

Here's one way:

tmp=$(mktemp)
while IFS=';' read -r file rest; do
   [ -f "$file" ] && printf '%s;%s\n' "$file" "$rest"
done < file.txt > "$tmp" &&
mv "$tmp" file.txt

or if you don't want a temp file for some reason:

tmp=()
while IFS=';' read -r file rest; do
   [ -f "$file" ] && tmp+=( "$file;$rest" )
done < file.txt &&
printf '%s\n' "${tmp[@]}" > file.txt

Both are untested but should be very close if not exactly correct.

Upvotes: 2

dwright
dwright

Reputation: 504

If I understand, this should do it.

touch file.txt file2.txt

for i in `cat file.txt`; do
  fp=`echo $i|cut -d ';' -f2`
   if [ -e $fp ];then
       echo "$i" >> file2.txt
   fi
done
mv file2.txt file.txt

Upvotes: 0

Related Questions