Issue
I got a list of files with my grip results.
$ grep -il 'name:red' */*/doc.txt
current_dir/Big_A/Folder1/doc.txt
current_dir/Big_A/Folder2/doc.txt
current_dir/Big_C/Folder5/doc.txt
I'd now like to move the entire folders that matched my result somewhere else and rename based on the contents in their doc file. While I had sucessfully grepped the name I want with
$ grep -i 'name:red' */*/doc.txt | cut -f2- -d:
Red Bucket
Red Asparagus
Red Blueberries
I'm drawing a blank on removing just the final filename so I can move entire folders.
I have tried some piping it with cut but can't find a working method that lets me cut on the correct position given that rev isn't supported in gitbash and cut --output-delimiter=doc
did absoutely nothing.
Edit: 20 seconds after posting I found sed 's/search/replace' which solved the first half.
So this is the result I want.
current_dir/Mars/Red Bucket/doc.txt
current_dir/Mars/Red Asparagus/doc.txt
current_dir/Mars/Red Blueberries/doc.txt
Solution
This is rather unclear really. But something like this perhaps?
#!/bin/Bash
grep -il 'name:red' */*/doc.txt |
while IFS='' read -r matched; do
folder=${matched%/*}
newdest=$(grep -i -m1 'name:red' "$matched")
echo mv ./"$folder" current_dir/Mars/"$newdest"
done
If this looks like what you wanted, remove the echo
to make it actually run mv
.
The reason cut
doesn't work on a string is that it just allows for a single-character delimiter. Here, we instead use the shell's built in parameter expansion facility to trim the suffix from the file name.
We use grep -m 1
to only print the first match in each file. If you know there can only be one match in each file, you can take that out. If you can specify a more constrained regex to make sure you only get one match, maybe use sed
or Awk instead of grep
to fetch the interesting part out of a longer pattern match. For example,
newdest=$(sed -n 's%.*<tag attrib="name:red">\([^<>]*\)</tag>.*%\1%p' "$matched")
to fetch the interesting string out of an XML-like tag structure. (Though processing XML with line-oriented regex tools is brittle and complex; if your input is really XML, maybe use a proper XML parser for this.)
Answered By - tripleee Answer Checked By - Candace Johnson (WPSolving Volunteer)