【问题标题】:Insert changing string from filename at the beginning of every line in terminal在终端的每一行的开头插入来自文件名的更改字符串
【发布时间】:2015-09-04 09:51:10
【问题描述】:

我对 bash 的经验为零,所以我在语法上苦苦挣扎——我放弃了在 python 中的尝试,因为我认为它可能更容易。我想提取文件名的一部分(在 .xyz 扩展名之前和前缀之后),将其插入每一行(从第三行开始)并将输出通过管道传输到一个新文件。我也想对字符串发生变化的多个文件执行此操作。

我的输入文件如下:

blahblah-0.xyz
blahblah-1.xyz
blahblah-2xyz

到目前为止,我知道我可以做到:

sed '3,$ s/^/500 /' file-500.xyz > output

这将在每一行插入字符串。但我不想为每个目录做 100 次!我还从这里尝试了以下操作:awk parse filename and add result to the end of each line:

 for filename in ratio*; do 
   num=$(echo $filename | grep -Eo '[^ratio_distances]+\.xyz' | cut -d. -f1)
   sed -i "s/\^/\t$num" $filename
 done

补充一下,这只是在标准 mac 终端中执行,因为我遇到了关于 'sed -i' 命令的错误。

编辑:

我让它在 python 中工作,但我仍然有兴趣了解 bash 命令。 Python 代码应该在同一件事之后:

import sys
import os
import glob

list_of_files = glob.glob("./blah-blah*.xyz")
for file in list of files:
    for i in range (0, 80):
        P = 10*i
        if str(P) in file:
            with open(file, 'r') as infile:
                lines = infile.readlines()
                lines[:]=lines[2:]
             lines = [str(P)+' '+line for line in lines]
             with open(file.replace('blahblah','output'),'w') as outfile:
                 outfile.writelines(lines)
             infile.close()
             outfile.close()

非常感谢您的任何见解, 安娜

【问题讨论】:

    标签: python bash awk sed


    【解决方案1】:

    假设您可以在旧文件名前加上“new_”来创建新文件名:

    awk '
        FNR==1 { pfx = FILENAME; sub(/.*\./,"",pfx) }
        FNR>=3 { $0 = pfx $0 }
        { print > ("new_"FILENAME) }
    ' ratio*
    

    【讨论】:

      【解决方案2】:

      您可以使用 bash 的参数扩展从文件名中提取数字。 Mac 的 sed 不支持-i,所以你必须使用临时文件:

      #! /bin/bash
      for filename in ratio* ; do
          num=${filename#ratio_distances-}  # Remove from the left.
          num=${num%.xyz}                   # Remove from the right.
          sed "3,\$ s/^/$num /" "$filename" > new"$num"
          mv new"$num" "$filename"          # Replace the original with the tempfile.
      done
      

      【讨论】:

        【解决方案3】:
        #!/bin/bash
        PrefixFile="blahblah"
        awk -v "Prefix=${PrefixFile}" '
           # At each new file starting
           FNR == 1 {
              # take number from current file name
              gsub( "^" Prefix "-|[.]xyz$", "", Index = FILENAME)
              }
           # at each line (so for every files)
           {
              # print the index file (current) followed by original line
              # to the (corresponding) filename.New
              print Index $0 > ( FILENAME ".New" )
           }
           ' ${PrefixFile}*.xyz
        
        • 使用 awk,从 shell 扩展一次使用所有文件
          • 假设前缀没有-(如果没有的话很容易适应)
        • 输出可以是除自身之外的任何其他文件(修改 aw 也可以在末尾更改名称,但在 bash 本身中更好)

        感谢 @EdMorton 提供有关 awk 关于文件重定向的行为的额外信息

        【讨论】:

        • 为了可移植性,您需要将输出重定向右侧的任何表达式括起来,所以它是print > (foo bar),而不是print > foo bar,因为它不是由POSIX定义的,所以一些awks假设后者意味着@ 987654325@。此外,您想要的操作只是 >,而不是 >> - awk 中的语义与 shell 中的不同。
        • 不知道()。对于>>,我从 sed AWK 编程语言 中获取它,在 print 或 printf 之后指定 >>。将进行一些测试:-​​) 反正+1
        • 在 shell 和 awk 中,> 表示“覆盖文件”,而 >> 表示“附加到文件”,但在 shell 中,在每个打印语句中都会评估覆盖与附加,而在 awk 中它是在脚本启动时进行评估。因此,当您在 shell 中编写 for i in $(seq 1..10); do printf "x" > file; done 时,您最终会得到包含单个 x 的 file,而在 awk 中,如果您编写 for (i=1;i<=10;i++) printf "x" > file,您最终会得到包含 10 个 xs 的 file。如果你写了for (i=1;i<=10;i++) printf "x" >> file,你最终会得到一个文件,其中包含它在 awk 脚本运行之前所做的一切,然后是 10 xs
        • 感谢您提供详尽的信息,将调整回复
        猜你喜欢
        • 2011-11-29
        • 2014-09-28
        • 1970-01-01
        • 2018-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-06
        相关资源
        最近更新 更多