我有一个文件如下:

line1
line2
line3

我想要得到:

prefixline1
prefixline2
prefixline3

我可以编写Ruby脚本,但如果我不需要这样做会更好。

前缀将包含/。为路径,例如“/opt/workdir/”。


当前回答

使用shell:

#!/bin/bash
prefix="something"
file="file"
while read -r line
do
 echo "${prefix}$line"
done <$file > newfile
mv newfile $file

其他回答

下面是一个使用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
# 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/'

如果你有Perl:

perl -pe 's/^/PREFIX/' input.file

如果你的前缀有点复杂,就把它放在一个变量中:

prefix=path/to/file/

然后,你传递这个变量,让awk来处理它:

awk -v prefix="$prefix" '{print prefix $0}' input_file.txt

艾德:使用

ed infile <<'EOE'
,s/^/prefix/
wq
EOE

对于每一行(,),它用前缀替换行(^)的开头。Wq保存并退出。

如果替换字符串包含斜杠,我们可以使用不同的分隔符代替s:

ed infile <<'EOE'
,s#^#/opt/workdir/#
wq
EOE

我引用了here-doc分隔符EOE(“end of ed”),以防止参数扩展。在这个例子中,不加引号也可以工作,但是如果ed脚本中出现$,这是一个很好的实践,可以防止出现意外。