Reputation:
I have an assignment that follows:
Loop through every file in ~files, check if the same file exists in ~oUser/files, if it does then move the file in oUser to .bkp. Once you've ensured the file does not exist copy the file from your home directory to oUser's home directory.
I have a hard time understanding the question but I started breaking it down one step at a time and I can not get past understanding how to find common files.
This is what I have done so far:
cd files
touch t1.txt
touch t2.txt
touch t3.txt
cd ~oUser/files
touch t2.txt
touch t4.txt
So I learned loop to be as:
for FILE in ~/files; do echo $FILE; done
for FILE in ~/oUser/files; do echo $FILE; done
I thought I can output the names into a specific file and then use grep for commonalities
find ~/files -type f > files.txt
find ~oUser/files -type f > oUserfiles.txt
grep -l files.txt oUserfiles.txt > file.txt
but when I open the file.txt
it's empty.
Upvotes: 0
Views: 697
Reputation: 535
I'm not going to write your assignment for you, but here is some information you may find useful.
Find
find
prints files that it finds prefaced by the path you give it. So, if you had the file example.txt
in ~/files/
, this would be printed by find ~/files -type f
as $HOME/files/example.txt
. This means that if you run find
in different folders, the outputs won't match, so even if grep
worked the way you interpreted (i.e. matching lines in files), it still wouldn't work because the paths are different.
Grep
grep
expects input in the form
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
as detailed in its man page. The -l
flag changes grep
s behaviour to just printing the names of files which match, so grep -l files.txt oUserfiles.txt
just checks if any line in oUserfiles.txt
matches the literal string files.txt
, and if it does then it outputs the literal string oUserfiles.txt
. I recommend reading that man page, but I will note that the -f
flag pulls patterns line by line from the first file, if you still want to do that.`
Checking file existence
You can check if a particular file exists using [ -e path/to/file.txt ]
. The spaces there are important, so don't omit those. In order to check in ~, and using a variable, you'll need something along the lines of [ -e ~/files/"$FILE" ]
, which allows bash to expand the ~
to $HOME
(Thanks to @Cyrus!).
Upvotes: 1