Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

grep - get filenames with paths that match a basename pattern

I have a list of filenames with their paths like this

/some/path/or/another/RCrandomname.TRI
/another/path/NCrandomname2.TRI
/one/more/path/RCrandomname3.PCD

I would like to pick only the filenames (with their paths) whose basename starts with RC and have extension TRI so in the above example I would like to get just

/some/path/or/another/RCrandomname.TRI

if I had the basename only I could do

ls | grep "^RC.*.TRI$" > filenames

but here I have all the paths. I have a requirement of using ls

question from:https://stackoverflow.com/questions/65925822/get-filenames-with-paths-that-match-a-basename-pattern

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't parse output of ls, it is error prone in many ways.

You can use globbing with shopt globstar:

shopt -s globstar
ls -1 **/RC*.TRI > filenames

globstar, When enabled, the globbing code treats ** specially -- it matches all directories (and files within them, when appropriate) recursively.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...