Python 如何多次粘贴2个文件或单个文件的内容?
我在shell脚本中主要使用一行程序 如果我有一个包含以下内容的文件:Python 如何多次粘贴2个文件或单个文件的内容?,python,shell,Python,Shell,我在shell脚本中主要使用一行程序 如果我有一个包含以下内容的文件: 1 2 3 并希望它像这样粘贴: 1 1 2 2 3 3 如何使用python one liner在shell脚本中实现这一点 PS:我尝试了以下方法:- python -c "file = open('array.bin','r' ) ; cont=file.read ( ) ; print cont*3;file.close()" 但它印刷的内容如下:- 1 2 3 1 2 3 您可以用以下内容替换print c
1
2
3
并希望它像这样粘贴:
1 1
2 2
3 3
如何使用python one liner在shell脚本中实现这一点
PS:我尝试了以下方法:-
python -c "file = open('array.bin','r' ) ; cont=file.read ( ) ; print cont*3;file.close()"
但它印刷的内容如下:-
1
2
3
1
2
3
您可以用以下内容替换
print cont*3
:
print '\n'.join(' '.join(ch * n) for ch in cont.strip().split())
此处
n
是列数。您需要将行拆分,然后重新组装:
一行:
python -c "file=open('array.bin','r'); cont=file.readlines(); print '\n'.join([' '.join([c.strip()]*2) for c in cont]); file.close()"
file=open('array.bin', 'r')
cont=file.readlines()
print '\n'.join([' '.join([c.strip()]*2) for c in cont])
file.close()
1
2
3
1 1
2 2
3 3
长格式:
python -c "file=open('array.bin','r'); cont=file.readlines(); print '\n'.join([' '.join([c.strip()]*2) for c in cont]); file.close()"
file=open('array.bin', 'r')
cont=file.readlines()
print '\n'.join([' '.join([c.strip()]*2) for c in cont])
file.close()
1
2
3
1 1
2 2
3 3
具有数组.bin
具有:
python -c "file=open('array.bin','r'); cont=file.readlines(); print '\n'.join([' '.join([c.strip()]*2) for c in cont]); file.close()"
file=open('array.bin', 'r')
cont=file.readlines()
print '\n'.join([' '.join([c.strip()]*2) for c in cont])
file.close()
1
2
3
1 1
2 2
3 3
给出:
python -c "file=open('array.bin','r'); cont=file.readlines(); print '\n'.join([' '.join([c.strip()]*2) for c in cont]); file.close()"
file=open('array.bin', 'r')
cont=file.readlines()
print '\n'.join([' '.join([c.strip()]*2) for c in cont])
file.close()
1
2
3
1 1
2 2
3 3
不幸的是,您不能对一行程序解决方案使用简单的for语句(如前面的答案中所建议的)。正如所解释的,“只要添加引入缩进块(如if)的构造,就需要换行。” 这里有一个可能的解决方案可以避免此问题:
- 删除尾随的新行字符
- 乘以列数
python -c "f = open('array.bin', 'r'); n = 5; print('\n'.join([line.strip()*n for line in list(f)])); f.close()"
来自命令propmt的第一个测试:
paste -d" " array.bin array.bin
编辑:OP希望使用一个变量n来显示需要多少列。 有不同的方法可以重复一个命令10次,例如
for i in {1..10}; do echo array.bin; done
seq 10 | xargs -I -- echo "array.bin"
source <(yes echo "array.bin" | head -n10)
yes "array.bin" | head -n10
我的解决办法是
paste -d" " $(printf "%*s" $n " " | sed 's/ /array.bin /g')
所有打印的数字都是水平的,但实际上是垂直的。虽然答案总是值得赞赏的,但它确实有助于提供一些关于代码如何解决手头问题的信息。请提供一些关于您的答案的上下文,并查看以获取有关如何编写优秀答案的信息:)您好,Walter,粘贴命令有效。这里的目的是粘贴文件的次数与变量“n”给定的文件次数相同,该变量的值是动态确定的。。。。。感谢使用
$n
的解决方案提交。