【发布时间】: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()
非常感谢您的任何见解, 安娜
【问题讨论】: