Wednesday, May 15, 2024
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 487  / 2 Years ago, fri, july 22, 2022, 4:10:37

For example I have a directory:


/A/B/C/D/E/F/G.txt

Not knowing a priori /E/F/G.txt, I need to isolate that part. For ease of example:


echo '/A/B/C/D/E/F/G.txt' | grep -o '/A/B/C/D'

Shows:


/A/B/C/D

But I want:


/E/F/G.txt

With:


echo '/A/B/C/D/E/F/G.txt' | grep -o -v '/A/B/C/D'

I don't get the desired output (the output is not there at all).


How can I get the desired output using grep, i.e. not showing the part of the line which is in the search terms of grep?


More From » command-line

 Answers
4

With PCRE expressions, you can specify a pattern but exclude it from the match using K:


% echo '/A/B/C/D/E/F/G.txt' | grep -Po '/A/B/C/DK.*'
/E/F/G.txt

However, if this is actually for files and directories, I'd suggest using find instead:


% mkdir -p A/B/C/D/E/F
% touch A/B/C/D/E/F/G.txt
% find A/B/C/D -type f -printf "%P
"
E/F/G.txt

Or if you really want the leading slash:


% find A/B/C/D -type f -printf "/%P
"
/E/F/G.txt

From the find documentation:



%P

File’s name with the name of the
command line argument under which it was found removed from the
beginning.



[#693] Friday, July 22, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
algicuade

Total Points: 317
Total Questions: 89
Total Answers: 106

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;