bash 如何同时grep和cut

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6416057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:13:06  来源:igfitidea点击:

How to grep and cut at the same time

bashgrepcut

提问by Johnathon

Having trouble with grepping and cutting at the same time I have a file test.txt. Inside the file is this syntax

在同时进行 grepping 和 cut 时遇到问题,我有一个文件test.txt. 文件里面是这个语法

File: blah.txt Location: /home/john/Documents/play/blah.txt
File: testing.txt Location /home/john

My command is ./delete -r (filename), say filename is blah.txt.

我的命令是./delete -r (filename),说文件名是blah.txt.

How would i search test.txtfor blah.txtand cut the /home/john/Documents/play/blah.txtout and put it in a variable

如何将我搜索test.txtblah.txt和切/home/john/Documents/play/blah.txt出,并把它放在一个变量

回答by Blagovest Buyukliev

grep -P "^File: blah\.txt Location: .+" test.txt | cut -d: -f3

回答by dimba

Prefer always to involse as less as possible external command for your task.

最好总是为您的任务使用尽可能少的外部命令。

You can achive what you want using singleawkcommand:

您可以使用单个awk命令实现您想要的:

awk '/^File: blah.txt/ { print  }' test.txt

回答by Loukan ElKadi

Try this one ;)

试试这个 ;)

filename=$(grep 'blah.txt' test.txt | grep -oP 'Location:.*' | grep -oP '[^ ]+$')
./delete $filename