如何找到特定字符串的正则表达式 [英] how to find a regular expression of specific string
问题描述
我有一个与正则表达式有关的问题.我有一个巨大的文本文件,例如
I have a question related to a regular expression. I have a huge text file like
我想要得到这样的输出
ID DE
1.1 Transformer
1.12 Best bye
1.1.1 Iphone
所以基本上我想获得ID和DE
so basically I want to get ID and DE
我尝试过使用awk和sed,但没有成功.我以为我先得到ID,然后再得到DE,然后合并它们,但是我仍然不知道该怎么做
what I tried was using awk and sed but with no success. I thought I get the ID and then I get the DE and then I merge them but I still could not figure out how to do that
sed -n ID my.txt
sed -n ID my.txt
我使用了 -n ,因为默认情况下,在所有命令都应用到标准输出后,每一行都会回显到标准输出.
I used -n because By default, each line of input is echoed to the standard output after all of the commands have been applied to it.
推荐答案
如OP所述,如果任何de
为空且相应的id
为空,则打印连字符,然后尝试执行以下操作.
As OP mentioned in case any de
is empty with respective id
then print an hyphen, then try following.
awk '
BEGIN{
OFS="\t"
print "ID\t\tDE"
}
/ID/{
if(id){
print id,de?de:"-"
id=de=""
}
id=$2
next
}
/DE/{
$1=""
sub(/^ +/,"")
de=$0
}
END{
if(id){
print id,de?de:"-"
}
}' Input_file
请您试一下.
Could you please try following.
awk '
BEGIN{
OFS="\t"
print "ID\t\tDE"
}
/ID/{
if(id){
print id,de
id=de=""
}
id=$2
next
}
/DE/{
$1=""
sub(/^ +/,"")
de=$0
}
END{
if(id){
print id,de
}
}' Input_file
这篇关于如何找到特定字符串的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!