【问题标题】:How connect words in a text file如何连接文本文件中的单词
【发布时间】:2013-08-26 03:19:04
【问题描述】:

我有一个格式如下的文件:

B: that


I: White


I: House


B: the
I: emergency


I: rooms


B: trauma
I: centers

我需要做的是从顶部逐行读取,如果该行以 B 开头,则删除 B: 如果它以 I: 开头,则删除 I: 并连接到前一个(前一个在同一规则中处理)。

预期输出:

that White House
the emergency rooms
trauma centers

我尝试了什么:

while read line
do
    string=$line

    echo $string | grep "B:"  1>/dev/null 
    if [ `echo $?` -eq 0 ] //if start with " B: "
    then
        $newstring= echo ${var:4} //cut first 4 characters which including B: and space

        echo $string | grep "I:"  1>/dev/null 
    if [ `echo $?` -eq 0 ] //if start with " I: "
    then
        $newstring= echo ${var:4} //cut first 4 characters which including I: and space
done < file.txt

我不知道的是如何将它放回线路(在文件中)以及如何将线路连接到之前处理的线路。

【问题讨论】:

    标签: unix sed awk grep cut


    【解决方案1】:

    使用 awk 打印 I:B: 记录的第二个字段。变量first用于控制换行输出。

    /B:/ 搜索B: 模式。这种模式标志着记录的开始。如果记录不是第一个,则打印一个换行符,然后打印数据 $2。

    如果找到的模式是I:,则数据$2(打印I: 之后的第二个字段。

    awk 'BEGIN{first=1}
         /B:/ { if (first) first=0; else  print "";  printf("%s ", $2); }
         /I:/ { printf("%s ", $2) }
         END {print ""}' filename
    

    【讨论】:

    • 是的,它有效!这也是非常好的和简短的答案,如果有关于参数的评论,那就完美了!
    • 添加了更多叙述 - 希望对您有所帮助。
    【解决方案2】:
    awk -F":" '{a[NR]=$0}
               /^ B:/{print line;line=$2}
               /^ I:/{line=line" "$2}
               END{
                   if(a[NR]!~/^B/)
                   {print line}
              }' Your_file
    

    【讨论】:

      【解决方案3】:
      awk '/^B/ {printf "\n%s",$2} /^I/ {printf " %s",$2}' file
      
      that White House
      the emergency rooms
      trauma centers
      

      缩短一点

      awk '/./ {printf /^B/?"\n%s":" %s",$2}' file
      

      【讨论】:

      • 谢谢,如果允许接受两个答案我会选择你。但我必须以最快的速度回答。
      • 没问题,你仍然可以点击向上箭头(这个答案很有用):)
      【解决方案4】:

      有一个在 RS 模式上使用 awk 自动拆分的有趣解决方案。请注意,这对输入格式的变化有点敏感:

      <infile awk 1 RS='(^|\n)B: ' | awk 1 RS='\n+I: ' ORS=' ' | grep -v '^ *$'
      

      输出:

      that White House
      the emergency rooms
      trauma centers
      

      这至少适用于 GNU awk 和 Mikes awk。

      【讨论】:

        【解决方案5】:

        这可能对你有用(GNU sed):

        sed -r ':a;$!N;s/\n$//;s/\n\s*I://;ta;s/B://g;s/^\s*//;P;D' file
        

        或:

        sed -e ':a' -e '$!N' -e 's/\n$//' -e 's/\n\s*I://' -e 'ta' -e 's/B://g' -e 's/^\s*//' -e 'P' -e 'D' file
        

        【讨论】:

        • 我使用 Mac,它说:sed: 非法选项 -- r
        • @user1314404 它不需要-r 选项,但是当您使用Mac 时,您可能需要分隔每条指令并使用-e 标志。见编辑
        猜你喜欢
        • 2019-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-16
        • 1970-01-01
        • 2015-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多