简体   繁体   English

在终端的每一行的开头插入文件名中更改的字符串

[英]Insert changing string from filename at the beginning of every line in terminal

I have zero experience with bash so I'm struggling with the syntax - I gave up attempting in python as I thought that it might be easier. 我对bash的使用经验为零,所以我在语法上苦苦挣扎-我放弃了使用python的尝试,因为我认为这样做可能会更容易。 I would like to extract part of the filename (before the .xyz extension, and after the prefix), insert it on every line (starting from the third line) and pipe the output to a new file. 我想提取文件名的一部分(在.xyz扩展名之前和前缀之后),将其插入每行(从第三行开始)并将输出通过管道传输到新文件。 I would also like to do this for multiple files, where the string changes. 我还想对字符串更改的多个文件执行此操作。

My input files are as follows: 我的输入文件如下:

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

So far I know that I can do: 到目前为止,我知道我可以做到:

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

and this will insert the string on every line. 这将在每行上插入字符串。 But I don't want to do this 100 times for each directory! 但是我不想为每个目录执行100次! I also tried the following from here: awk parse filename and add result to the end of each line : 我还从这里尝试了以下方法: awk解析文件名并将结果添加到每行的末尾

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

Just to add, this is just being performed in the standard mac terminal, as I've had errors crop up in regards to the 'sed -i' command. 只是要补充一点,这只是在标准的Mac终端中执行的,因为关于“ sed -i”命令我遇到了很多错误。

EDIT: 编辑:

I got it to work in python, but I'd still be interested to know the bash commands. 我知道它可以在python中工作,但是我仍然对bash命令感兴趣。 Python code should any one else be after the same thing: 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()

Thanks very much for any insight, Anna 非常感谢您的任何见解,安娜

Assuming you can just prefix the old file names with "new_" to create the new file names: 假设您可以在旧文件名前面加上“ new_”作为新文件名:

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

You can use bash's parameter expansion to extract the number from the file name. 您可以使用bash的参数扩展从文件名中提取数字。 The -i is not supported in Mac's sed, so you have to use a temp file: 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
#!/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
  • Using awk, using all files at once from shell expansion 使用awk,一次使用shell扩展中的所有文件
    • assume prefix is without the - (easily adapteable if not) 假设前缀不带- (如果没有,则很容易适应)
  • ouput culd be any other file except itself (modification of aw could also change the name at the end but better in bash itself) 输出可以是除自身以外的任何其他文件(对aw的修改也可以在末尾更改名称,但使用bash更好)

Thanks to @EdMorton for extra info about behaviour of awk about file redirection 感谢@EdMorton提供有关有关文件重定向的awk行为的额外信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在每一行的开头插入字符串 - Insert string at the beginning of each line 在python中的每个空白行上插入新行字符串 - Insert a new line string on every blank line in python 在python中的regex开头插入字符串 - insert string at beginning of regex in python Python 3.7 - 在文件夹中 all.txt 文件的每一行开头插入文件名 - Python 3.7 - insert filename at the start of every line in all .txt files in a folder Python:如何从字符串的开头删除空引号和新行? - Python: How to remove empty quotes and a new line from the beginning of the string? Python - 写入TXT中每行的开头和结尾 - Python - Write To Beginning and End of Every Line in TXT 在Python行首匹配一个字符串 - match a string at the beginning of the line in Python 在Python中,有没有一种方法可以插入换行符并在字符串的每68个字符之间插入空格? - In Python, is there a way to insert a line break and spaces every 68 characters of a string? 如何使用 Python 中的正则表达式捕获从字符串开头到每次出现特定字符串/模式的所有内容? - How to capture everything from the beginning of a string until every occurrence of a specific string/pattern using regular expressions in Python? 删除python文件中每个字符串开头的空格? - Remove whitespaces in the beginning of every string in a file in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM