我希望在 python 或基本 shell 脚本中执行此操作。
我有一个包含多个条目的文件,我想操纵它的数据并将它们存储在变量中。
该文件包含多列行。第一列是一个人的名字(即 Joe、Mary 等)。第二个(在逗号之后)是一个 ID。我想将每个 ID 存储到一个变量中,然后构建一些链接,如下所示。问题是一个名字只能有一个 ID 或多个,如下所示:
Joe, 21142 21143 21909 24125
Mary, 22650 23127
John, 24325
Mike, 24683 24684 26973
我怎样才能将“第二列”中的每个值存储到一个变量中,这样我就可以像这样构建链接:
http://example/Joe/21142
http://example/Joe/21143
http://example/Joe/21909
http://example/Joe/24125
http://example/Mary/22650
http://example/Mary/23127
提前致谢!
- 奥马尔
请您参考如下方法:
可以用 GNU awk 完成
awk -F'[, ]+' '{for (i=2; i<=NF; ++i) print "http://example/"$1"/"$i }' input.txt
http://example/Joe/21142
http://example/Joe/21143
http://example/Joe/21909
http://example/Joe/24125
http://example/Mary/22650
http://example/Mary/23127
http://example/John/24325
http://example/Mike/24683
http://example/Mike/24684
http://example/Mike/26973
或者在 Python 中
s = '''Joe, 21142 21143 21909 24125
Mary, 22650 23127
John, 24325
Mike, 24683 24684 26973
'''
from StringIO import StringIO
from contextlib import closing
with closing(StringIO(s)) as f:
for line in f:
x, y = line.split(',')
x = x.strip()
y = y.strip().split()
leader = 'http://example/{}'.format(x)
print '\n'.join('{}/{}'.format(leader, z) for z in y)
