我對此有點困惑,不知道如何在整個檔案中找到關鍵字并進行匹配,應該列印整個單詞。
假設我想搜索關鍵字: file_demo
下面資料中唯一匹配的詞是file_demo_2021.txt
輸出應該是: file_demo_2021.txt
以下是我在檔案中的資料:
幾代人以來,非洲的故事傳統上都是口耳相傳。通常,經過一天的辛苦作業后,大人們會在月光下將孩子們聚集在一起,圍著村莊的火堆講故事。這在傳統上被稱為“月光下的故事”。通常,這些故事旨在讓年輕人為生活做好準備,因此每個故事都教導了一個教訓或道德。file_demo_2021.txt 在非洲民間故事中,故事反映了各種動物比比皆是的文化。動物和鳥類通常被賦予人類屬性,因此經常會發現動物會說話、唱歌或表現出其他人類特征,例如貪婪、嫉妒、誠實等。許多故事中的背景將讀者暴露在土地上非洲該地區的形態和氣候。
在此資料中,這是一個檔案名,我需要將其列印如下:
輸出 :
file_demo_2021.txt
uj5u.com熱心網友回復:
只需使用 grep
grep -oP "file_demo.*\.txt" filename
查找任何 file_demo*.txt
grep -oP "file_demo.*[\s]" filename
查找任何 file_demo.* 直到單詞分隔符(空格、逗號、字串結尾等)
uj5u.com熱心網友回復:
GNUAWK解決方案。讓file.txt內容成為
For several generations, stories from Africa have traditionally been passed down by word of mouth. Often, after a hard day’s work, the adults would gather the children together by moonlight, around a village fire and tell stories. This was traditionally called 'Tales by Moonlight'. Usually, the stories are meant to prepare young people for life, and so each story taught a lesson or moral. file_demo_2021.txt In the African folktales, the stories reflect the culture where diverse types of animals abound. The animals and birds are often accorded human attributes, so it is not uncommon to find animals talking, singing, or demonstrating other human characteristics such as greed, jealousy, honesty, etc. The setting in many of the stories exposes the reader to the land form and climate within that region of Africa. References are often made to different seasons such as the 'dry' or 'rainy' season and their various effects on the surrounding vegetation and animal life.
然后
awk 'BEGIN{RS="[[:space:]]"}/file_demo/' file.txt
輸出
file_demo_2021.txt
說明:我通知 AWK 使用任何空格作為行分隔符 ( RS),因此我每行得到一個單詞。如果所述行匹配file_demo默認操作被采取- printing。
(在 GNU Awk 5.0.1 中測驗)
uj5u.com熱心網友回復:
使用 GNU sed。
編輯
如果檔案太大,這可能效率不高,因為整個檔案都被讀入記憶體。
sed -Ez 's/.* ([a-z]*file_demo[^, ]*).*/\1\n/'
uj5u.com熱心網友回復:
隨著GNUawk使用patsplit():
awk 'patsplit($0,vals,/([[:alpha:]] _){2}[[:digit:]] [.][[:alpha:]] /) { for (i in vals) print vals[i] }' file
file_demo_2021.txt
- 您可以查看 Ed Morton 有關
why does patsplit() exist?轉到 https://groups.google.com/g/comp.lang.awk/c/kBXXXeWMz-Y 的示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/317394.html
