Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

bash - 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

I want to get an output like this

 ID           DE
1.1      Transformer
1.12     Best bye
1.1.1    Iphone

so basically I want to get ID and 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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: As OP mentioned in case any de is empty with respective id then print an hyphen, then try following.

awk '
BEGIN{
  OFS="	"
  print "ID		DE"
}
/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="	"
  print "ID		DE"
}
/ID/{
  if(id){
    print id,de
    id=de=""
  }
  id=$2
  next
}
/DE/{
  $1=""
  sub(/^ +/,"")
  de=$0
}
END{
  if(id){
    print id,de
  }
}'   Input_file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...