How to use `while read -r line` and also check if there is an extra file in BASH?

I have a while loop simplified as follows:

while read -r line
do
    (delete some lines from file2.txt)
done < file.txt

If file2.txtempty, then this while loop no longer needs to work.

In other words, I need this:

while read -r line AND file2.txt IS NOT EMPTY
do
    (delete some lines from file2.txt
done < file.txt

I tried combining while read -r linewith -s file2.txt, but the result does not work:

while [ read -r line ] || [ -s file2.txt ]
do
    (delete some lines from file2.txt)
done < file.txt

How can I use this while loop to read lines in a file and also check that another file is not empty?

+4
source share
5 answers

Combine reading and test as:

while read -r line && [ -s file2.txt ]
do
  # (delete some lines from file2.txt)
  echo "$line"
done <file.txt

This will check before each iteration of the loop whether it is file2.txtnonempty.

+11
source

Useless use of a cat would make it easier here:

while read -r line
do
    (delete some lines from file2.txt)
done < <(test -s file2.txt && cat file.txt)

$ cat file.txt
foo
bar
baz
$ cat file2.txt
something
$ while read -r line; do echo "$line"; done < <(test -s file2.txt && cat file.txt)
foo
bar
baz
$ > file2.txt
$ while read -r line; do echo "$line"; done < <(test -s file2.txt && cat file.txt)
$
+3

- :

while read -r lf1 && [[ -s "path/to/file2" ]] && read -r lf2 <&3; do 
   echo "$lf1"; echo "$lf2"
done <file1 3<file2

, while.

:

<~/Temp>$ cat file1
line from file1
line2 from file1

<~/Temp>$ cat file2
I am not empty
Yep not empty

<~/Temp>$ while read -r lf1 && [[ -s "/Volumes/Data/jaypalsingh/Temp/file2" ]] && read -r lf2 <&3; do echo "$lf1"; echo "$lf2"; done <file1 3<file2
line from file1
I am not empty
line2 from file1
Yep not empty

<~/Temp>$ >file2

<~/Temp>$ while read -r lf1 && [[ -s "/Volumes/Data/jaypalsingh/Temp/file2" ]] && read -r lf2 <&3; do echo "$lf1"; echo "$lf2"; done <file1 3<file2
<~/Temp>$ 
+2

while read -r line
do
    [ ! -s file2.txt ] && break
    # (delete some lines from file2.txt)
done <file.txt

, , . , - , . , . , , , , , break - , , , , , , , "STOP", . , while read -r lineare such common idioms that they are essentially the software equivalent of common street signs. You will immediately recognize them, without mentally disassembling them. In any case, as I said, this is just my personal business. Do not be shy.

+2
source

slightly optimizing the answer given by Joe

while [ -s file2.txt ] && read -r line
do
  # (delete some lines from file2.txt)
done <file.txt
+1
source

Source: https://habr.com/ru/post/1529347/


All Articles