我有一个文件如下:
line1
line2
line3
我想要得到:
prefixline1
prefixline2
prefixline3
我可以编写Ruby脚本,但如果我不需要这样做会更好。
前缀将包含/。为路径,例如“/opt/workdir/”。
我有一个文件如下:
line1
line2
line3
我想要得到:
prefixline1
prefixline2
prefixline3
我可以编写Ruby脚本,但如果我不需要这样做会更好。
前缀将包含/。为路径,例如“/opt/workdir/”。
当前回答
下面是一个使用sed方法的示例:
$ cat /path/to/some/file | prefix_lines "WOW: "
WOW: some text
WOW: another line
WOW: more text
prefix_lines
function show_help()
{
IT=$(CAT <<EOF
Usage: PREFIX {FILE}
e.g.
cat /path/to/file | prefix_lines "WOW: "
WOW: some text
WOW: another line
WOW: more text
)
echo "$IT"
exit
}
# Require a prefix
if [ -z "$1" ]
then
show_help
fi
# Check if input is from stdin or a file
FILE=$2
if [ -z "$2" ]
then
# If no stdin exists
if [ -t 0 ]; then
show_help
fi
FILE=/dev/stdin
fi
# Now prefix the output
PREFIX=$1
sed -e "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/'
如果你有Perl:
perl -pe 's/^/PREFIX/' input.file
艾德:使用
ed infile <<'EOE'
,s/^/prefix/
wq
EOE
对于每一行(,),它用前缀替换行(^)的开头。Wq保存并退出。
如果替换字符串包含斜杠,我们可以使用不同的分隔符代替s:
ed infile <<'EOE'
,s#^#/opt/workdir/#
wq
EOE
我引用了here-doc分隔符EOE(“end of ed”),以防止参数扩展。在这个例子中,不加引号也可以工作,但是如果ed脚本中出现$,这是一个很好的实践,可以防止出现意外。
你可以在Ex模式下使用Vim:
ex -sc '%s/^/prefix/|x' file
%选择所有行 年代取代 保存并关闭
下面是一个使用sed方法的示例:
$ cat /path/to/some/file | prefix_lines "WOW: "
WOW: some text
WOW: another line
WOW: more text
prefix_lines
function show_help()
{
IT=$(CAT <<EOF
Usage: PREFIX {FILE}
e.g.
cat /path/to/file | prefix_lines "WOW: "
WOW: some text
WOW: another line
WOW: more text
)
echo "$IT"
exit
}
# Require a prefix
if [ -z "$1" ]
then
show_help
fi
# Check if input is from stdin or a file
FILE=$2
if [ -z "$2" ]
then
# If no stdin exists
if [ -t 0 ]; then
show_help
fi
FILE=/dev/stdin
fi
# Now prefix the output
PREFIX=$1
sed -e "s/^/$PREFIX/" $FILE