I have a text file:
$100 Birthday
$500 Laptop
$50 Phone
I created a --checklist from the text file
[ ] $100 Birthday
[*] $500 Laptop
[*] $50 Phone
the output is $100 $50
How can I delete the line of $100 and $50 in the text file, please?
The expected output of text file:
$100 Birthday
Thank you!
CodePudding user response:
with grep
and cut
grep -xf <(grep '\[ ]' file2.txt | cut -d\ -f3-) file1.txt
with grep
and sed
grep -xf <(sed -rn 's/\[ ]\s (.*)/\1/p' file2.txt) file1.txt
explanation
use grep
to select lines from text file
$ grep Birthday file1.txt
100 Birthday
cut
will split line into columns. -f 2
will print only 2nd column but -f 2-
will print everything from 2nd column. as delimiter -d
whitespace \
is used here (some character must escaped with \
)
we can use pipe |
as input instead file
$ echo one two three | cut -d \ -f 2-
two three
$ grep Birthday file1.txt | cut -d \ -f 2-
Birthday
assuming we have a text file temp.txt
$ cat temp.txt
Birthday
Laptop
Phone
grep
can also read list of search patterns from another file as input instead
$ grep -f temp.txt file1.txt
100 Birthday
500 Laptop
50 Phone
or we print the file content with cat
and redirect output with <
$ grep -f <(cat temp.txt) file1.txt
100 Birthday
500 Laptop
50 Phone
Now let's generate temp.txt
from checklist. You only want grep lines containing [ ]
and cut starting from 3rd column (again some characters have special meaning and must therefore escaped \[
)
$ grep '\[ ]' file2.txt
[ ] 100 Birthday
$ grep '\[ ]' file2.txt | cut -d\ -f3-
100 Birthday
You don't need temp.txt
and can therefore redirect list straight to grep -f
what is called process substitution <(...)
$ grep -f <(grep '\[ ]' file2.txt | cut -d\ -f3-) file1.txt
100 Birthday
grep
read all lines from temp.txt
as PATTERN and some characters have special meaning for regex. ^
stands for begin of line and $
for end of line. To be nitpicky correct search pattern should therefore be '^100 Birthday$'
so it won't match "1100 Birthday 2".
You might have noticed that I dropped the $ currency in your input files for reason. You can keep it, but tell grep
to take all input literally with -F
and(/or?) -x
flag which will search for whole line "100 Birthday" (no regex for line start/ending needed)
(... to be continued)