我有一个文件如下:
line1
line2
line3
我想得到:
prefixline1
prefixline2
prefixline3
我可以写一个Ruby脚本,但如果我不需要它会更好。
prefix
将包含/
。这是一条路,例如/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
如果prefix
包含/
,你可以使用不在prefix
中的任何其他字符,或者逃避/
,所以sed
命令变为
's#^#/opt/workdir#'
# or
's/^/\/opt\/workdir/'
以下是使用sed
的this answer方法的一个完整示例:
$ cat /path/to/some/file | prefix_lines "WOW: "
WOW: some text
WOW: another line
WOW: more text
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
有一个名为lam
的标准unix实用程序,是层压板的缩写。 lam -s prefix file
会做你想要的。我在管道中使用它,例如:
find -type f -exec lam -s "{}: " "{}" \; | fzf
...将找到所有文件,exec lam on each,给每个文件一个自己文件名的前缀。 (并将输出泵送到fzf进行搜索。)
awk '$0="prefix"$0' file > new_file
使用Perl(就地替换):
perl -pi 's/^/prefix/' file
您可以在Ex模式下使用Vim:
ex -sc '%s/^/prefix/|x' file
%
选择所有线路s
取代x
保存并关闭如果您的前缀有点复杂,只需将其放在变量中:
prefix=path/to/file/
然后,你传递该变量并让awk处理它:
awk -v prefix="$prefix" '{print prefix $0}' input_file.txt
如果你有Perl:
perl -pe 's/^/PREFIX/' input.file
使用shell:
#!/bin/bash
prefix="something"
file="file"
while read -r line
do
echo "${prefix}$line"
done <$file > newfile
mv newfile $file
虽然我不认为pierr有这个问题,但我需要一个不会延迟文件实时“尾部”输出的解决方案,因为我想同时监视多个警报日志,在每行前面加上其各自日志的名称。
不幸的是,sed,cut等引入了太多的缓冲并使我无法看到最新的线条。 Steven Penny建议使用-s
的nl
选项是有趣的,并且测试证明它没有引入与我有关的不需要的缓冲。
但是,使用nl
时存在一些问题,这与排除不需要的行号的愿望有关(即使你不关心它的美学,也许有些情况下使用额外的列是不可取的) 。首先,使用“剪切”去除数字会重新引入缓冲问题,因此它会破坏解决方案。其次,使用“-w1”没有帮助,因为这不会将行号限制为单个列 - 它只会随着需要更多数字而变宽。
如果你想在其他地方捕获它,这并不漂亮,但因为这正是我不需要做的事情(一切都已经写入日志文件,我只是想实时观看几个),最好的丢失行号的方法,只有我的前缀是用回车符(CR或^ M或Ctrl-M)启动-s
字符串。例如:
#!/bin/ksh
# Monitor the widget, framas, and dweezil
# log files until the operator hits <enter>
# to end monitoring.
PGRP=$$
for LOGFILE in widget framas dweezil
do
(
tail -f $LOGFILE 2>&1 |
nl -s"^M${LOGFILE}> "
) &
sleep 1
done
read KILLEM
kill -- -${PGRP}
这是一个使用来自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
使用ed:
ed infile <<'EOE'
,s/^/prefix/
wq
EOE
对于每一行(,
),这个替换为^
的行(prefix
)的开头。 wq
保存并退出。
如果替换字符串包含斜杠,我们可以为s
使用不同的分隔符:
ed infile <<'EOE'
,s#^#/opt/workdir/#
wq
EOE
我引用了here-doc分隔符EOE
(“end of ed”)来防止参数扩展。在这个例子中,它也可以不加引号,但如果你的ed脚本中有$
,那么防止意外是很好的做法。