我有一个文件如下:

line1
line2
line3

我想要得到:

prefixline1
prefixline2
prefixline3

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

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


当前回答

使用&(与模式"匹配的整个输入部分):

cat in.txt | sed -e "s/.*/prefix&/" > out.txt

或者使用反向引用:

cat in.txt | sed -e "s/\(.*\)/prefix\1/" > out.txt

其他回答

awk '$0="prefix"$0' file > new_file

在awk中,默认操作是'{print $0}'(即打印整行),因此上面的操作相当于:

awk '{print "prefix"$0}' file > new_file

使用Perl(就地替换):

perl -pi 's/^/prefix/' 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/'

使用Pythonize (pz):

pz '"preix"+s' <filename

对于使用BSD/OSX系统的人来说,有一个实用程序叫做lam,是laminate的缩写。Lam -s前缀文件将做你想做的。我把它用在管道上,例如:

查找type f -exec lam -s "{}: " "{}" \;| fzf

...这将找到所有的文件,exec lam对他们每个,给每个文件自己的文件名的前缀。(并将输出泵到fzf进行搜索。)

你可以用AWK来做

echo example| awk '{print "prefix"$0}'

or

awk '{print "prefix"$0}' file.txt > output.txt

对于后缀:awk '{打印$0"后缀"}'

对于前缀和后缀:awk '{打印“前缀”$0“后缀”}'