我有一个名为file的文件,其内容是
noise
noise
X noise STUFF1 noise STUFF2 noise
noise
Y noise STUFF3 noise
noise我断言X和Y是不同的,每个都在file中发生一次,X首先发生。
我能够发出一个sed命令来提取第一批信息,类似于
$ sed -n '/X/s/\(.*\)\(…\)\(.*\)\(…\)/\2 \4/p' < file
STUFF1 STUFF2
$ 还有一个类似的方法来提取STUFF3 (1),但我真正想做的是找到正确的sed咒语,以便
$ sed … < file
STUFF3 STUFF1 STUFF2
$(最后还可能学习!)sed的how缓冲器是如何工作的)。
(1)这不是一个关于正则表达式的问题,我知道如何隔离我所需要的文本片段。我需要保存我收集的信息,并在正确的时间输出它。
发布于 2022-05-21 12:24:44
使用sed
$ sed -n '/^X/{s/.[^[:upper:]]*\([[:alnum:]]*\)/\1 /g;h};/^Y/{s/.[^[:upper:]]*\([[:alnum:]]*\)/\1 /g;G;s/\n//p}' file
STUFF3 STUFF1 STUFF2$ cat script.sed
/^X/{ #Match line beginning with X
s/.[^[:upper:]]*\([[:alnum:]]*\)/\1 /g #As you know how to extract what you need, this is just for your sample data to extract needed strings
h #Retain the output of the substitution in the hold buffer
}
/^Y/{ #Match line beginning with Y
s/.[^[:upper:]]*\([[:alnum:]]*\)/\1 /g #Same as above
G #Append the contents of the hold space
s/\n//p #Remov the new line
}sed -nf script.sed file
STUFF3 STUFF1 STUFF2发布于 2022-05-21 13:17:31
sed -n ' # Do not print by default
/X/{
# pattern space holds 'X noise STUFF1 noise STUFF2 noise'
s/.*\(STUFF1).*\(STUFF2\).*/\1 \2/
# pattern space holds 'STUFF1 STUFF2'
# add stuff from pattern space to hold space with __leading newline__
H
# hold space holds '\nSTUFF1 STUFF2'
# use l to inspect
d
}
/Y/{
s/.*\(…\).*/\1/p
H
# hold space holds '\nSTUFF1 STUFF2\nSTUFF3'
d
}
${ # last line?
# switch hold space with pattern space
x
# we have '\nSTUFF1 STUFF2\nSTUFF3' in paterrn space, let's make it nice with spaces
s/\n/ /g
s/ */ /g
s/^ *//g
s/ *$//g
# print it
p
}
'发布于 2022-05-21 18:11:29
这可能对您有用(GNU sed):
sed -En '/^X/h;/^Y/{G;s/\s+/ /g;s/.*/echo "&"|cut -d" " -f3,7,9/ep}' file在“保持”空间中创建启动X的行的副本。
将副本附加到启动Y的行中。
用上线上的全局空格替换一个或多个空白。
使用cut命令将该行的内容替换为必需的列。
https://stackoverflow.com/questions/72329408
复制相似问题