我有一个文件如下:
line1
line2
line3
我想要得到:
prefixline1
prefixline2
prefixline3
我可以编写Ruby脚本,但如果我不需要这样做会更好。
前缀将包含/。为路径,例如“/opt/workdir/”。
我有一个文件如下:
line1
line2
line3
我想要得到:
prefixline1
prefixline2
prefixline3
我可以编写Ruby脚本,但如果我不需要这样做会更好。
前缀将包含/。为路径,例如“/opt/workdir/”。
当前回答
你可以在Ex模式下使用Vim:
ex -sc '%s/^/prefix/|x' file
%选择所有行 年代取代 保存并关闭
其他回答
使用Pythonize (pz):
pz '"preix"+s' <filename
使用shell:
#!/bin/bash
prefix="something"
file="file"
while read -r line
do
echo "${prefix}$line"
done <$file > newfile
mv newfile $file
# If you want to edit the file in-place
sed -i -e 's/^/prefix/' file
# If you want to create a new file
sed -e 's/^/prefix/' file > file.new
如果前缀包含“/”,则可以使用前缀以外的任何字符或 转义/,这样sed命令就变成了
's#^#/opt/workdir#'
# or
's/^/\/opt\/workdir/'
下面是一个使用moreutils的ts命令的高可读性的联机解决方案
$ cat file | ts prefix | tr -d ' '
以及它是如何一步步推导出来的:
# Step 0. create the file
$ cat file
line1
line2
line3
# Step 1. add prefix to the beginning of each line
$ cat file | ts prefix
prefix line1
prefix line2
prefix line3
# Step 2. remove spaces in the middle
$ cat file | ts prefix | tr -d ' '
prefixline1
prefixline2
prefixline3
在bash的命令行上使用for循环的简单解决方案:
for i in $(cat yourfile.txt); do echo "prefix$i"; done
将输出保存到一个文件:
for i in $(cat yourfile.txt); do echo "prefix$i"; done > yourfilewithprefixes.txt