我有一个文件如下:

line1
line2
line3

我想要得到:

prefixline1
prefixline2
prefixline3

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

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


当前回答

# 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/'

其他回答

如果您需要在每行具有特定字符串的开头预先添加文本,请尝试以下操作。在下面的例子中,我在每一行有“rock”的行开始添加#。

sed -i -e 's/^.*rock.*/#&/' file_name

你可以在Ex模式下使用Vim:

ex -sc '%s/^/prefix/|x' file

%选择所有行 年代取代 保存并关闭

你可以用AWK来做

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

or

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

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

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

# 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/'

您还可以使用反向引用技术来实现这一点 Sed -i.bak 's/\(.*\)/prefix\1/' foo.txt 你也可以像这样使用awk Awk '{print "prefix"$0}' foo.txt > TMP && mv TMP foo.txt