在awk中更改FS以匹配不是文件路径的任何内容

问题描述 投票:2回答:3

我正在尝试使用awk从程序的输出中提取文件路径。这是我第一次使用awk,我听说它对这种事情有好处,所以我点击了GNU手册:https://www.gnu.org/software/gawk/manual/gawk.html(awk符号链接到我的机器上gawk)

我正在尝试更改FS以使分隔符匹配任何不是文件路径的东西。我尝试了这种情况,我在输入中硬编码了2个文件路径:

awk -F '[^(\\/.)*]' '{print $1; print $2}'

我认为[^(\\/.)*]会将FS设置为匹配任何与文件路径不匹配的文本。我认为括号会阻止正则表达式被视为单个字符,例如[^abcd]。路径可以是他们想要的长度,因此也就是星号。这没用。

我的输入看起来像这样:

a whole bunch of random garbage oooh! a file /opt/dir/file and perhaps some more garbage and another file! /usr/local/bin

我希望输出像这样:

/opt/dir/file
/usr/local/bin

我将在Bash变量中捕获此预期输出。

有谁知道如何正确地做到这一点?如果我通过--posix命令,这也是有帮助的。注意:垃圾中可以存储任意数量的文件路径。

regex bash awk
3个回答
3
投票

如果要从某些文本中提取特定模式,请使用grep。要查找包含斜杠的所有单词:

grep -o '[^[:blank:]]*/[^[:blank:]]*'

使用GNU grep的pcre模式更容易阅读:

grep -oP '\S*/\S*'

其中\S\s(空白)的补充


3
投票

使用GNU awk和RT†:

$ awk 'BEGIN{RS="([^ ]*/[^ ]*)+"}{print RT}' file
/opt/dir/file
/usr/local/bin
[here be a nasty empty line]

RT #与记录分隔符RS表示的文本匹配的输入文本。每次读取记录时都会设置它。

编辑:你也可以使用GNU awk的splitseps(从\/开始注意/...\/.../):

$ awk ' {
    split($0,a,/([^ ]*\/[^ ]*)+/,seps)
    for(i in seps)
        print seps[i]
}' file
/opt/dir/file
/usr/local/bin

0
投票

以下awk也可以帮助你,在这里使用简单的match开箱即用的awk

awk '
{
while(match($0,/\/[a-zA-Z]+\/[^ ]*/)){
   print substr($0,RSTART,RLENGTH);
   $0=substr($0,RSTART+RLENGTH+1)}
}'  Input_file

说明:现在也为上面的代码添加说明。

awk '
{
while(match($0,/\/[a-zA-Z]+\/[^ ]*/)){  ##Starting a while loop here which will run till a match is found for REGEX present in match function
                                        ##in match function REGEX is there to match any kind of path which has slash in it and will match it till a space will come.
   print substr($0,RSTART,RLENGTH);     ##Printing the sub string on matched regex on current line subsring starts from RSTART to RLENGTH values.
                                        ##where RSTART and RLENGTH are match out of the box variables which will SET once a match found on match REGEX.
   $0=substr($0,RSTART+RLENGTH+1)}      ##Re-setting value of current line to substring which starts from value of till match found next character to till last of the line.
}'  Input_file                          ##Mentioning Input_file name here.
© www.soinside.com 2019 - 2024. All rights reserved.