Shell: How do I give a file the name of the parent directory?… here is a solution to the problem.
Shell: How do I give a file the name of the parent directory?
I’m a beginner in shell programming. I am currently writing a script to manipulate the found files. But I need to get the parent directory name of the found file. For example,
SEARCH_PATH=/home/test
for file in `find $SEARCH_PATH -name "pattern"`;
do
echo $file;
done
There are several folders in the search path that have file patterns
/home/test/type1/log/pattern
/home/test/type2/log/pattern
/home/test/type3/log/pattern
What I need to do is find the “pattern” in these files and match the name of the grandparent directory with the “type” name….
Solution
Dirty and fast :
kent$ dirname $(dirname "/home/test/type1/log/pattern")
/home/test/type1
If you don’t have /
in your filename, you can also use sed, awk cut…. An sed example:
kent$ echo "/home/test/type1/log/pattern"|sed 's#/[^/]*/[^/]*$##'
/home/test/type1
Edit
Enter only:
Base name and directory name:
kent$ basename $(dirname $(dirname "/home/test/type1/log/pattern"))
type1
Use awk:
kent$ echo "/home/test/type1/log/pattern"|awk -F'/' '$0=$(NF-2)'
type1