Linux 在每一行的开头添加一个前缀字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2099471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:41:45  来源:igfitidea点击:

Add a prefix string to beginning of each line

linuxscriptingtext-processing

提问by pierrotlefou

I have a file as below:

我有一个文件如下:

line1
line2
line3

And I want to get:

我想得到:

prefixline1
prefixline2
prefixline3

I could write a Ruby script, but it is better if I do not need to.

我可以写一个 Ruby 脚本,但如果我不需要,那就更好了。

prefixwill contain /. It is a path, /opt/workdir/for example.

prefix将包含/. /opt/workdir/例如,它是一条路径。

采纳答案by Alok Singhal

# 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

If prefixcontains /, you can use any other character not in prefix, or escape the /, so the sedcommand becomes

如果prefix包含/,则可以使用不在 中的任何其他字符prefix,或转义/,因此sed命令变为

's#^#/opt/workdir#'
# or
's/^/\/opt\/workdir/'

回答by Vijay

awk '
perl -pi 's/^/prefix/' file
="prefix"
#!/bin/bash
prefix="something"
file="file"
while read -r line
do
 echo "${prefix}$line"
done <$file > newfile
mv newfile $file
' file > new_file

With Perl(in place replacement):

使用 Perl(就地替换):

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

回答by ghostdog74

Using the shell:

使用外壳:

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

回答by Steven Penny

You can use Vim in Ex mode:

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

#!/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}
  1. %select all lines

  2. sreplace

  3. xsave and close

  1. %选择所有行

  2. s代替

  3. x保存并关闭

回答by Majid Azimi

If you have Perl:

如果你有 Perl:

prefix=path/to/file/

回答by ScriptGuy

While I don't think pierr had this concern, I needed a solution that would not delay output from the live "tail" of a file, since I wanted to monitor several alert logs simultaneously, prefixing each line with the name of its respective log.

虽然我不认为 pierr 有这个问题,但我需要一个不会延迟文件的实时“尾部”输出的解决方案,因为我想同时监视多个警报日志,在每一行前面加上各自日志的名称.

Unfortunately, sed, cut, etc. introduced too much buffering and kept me from seeing the most current lines. Steven Penny's suggestion to use the -soption of nlwas intriguing, and testing proved that it did not introduce the unwanted buffering that concerned me.

不幸的是,sed、cut 等引入了过多的缓冲,使我无法看到最新的行。Steven Penny 的使用-s选项的建议nl很有趣,测试证明它没有引入我所关心的不需要的缓冲。

There were a couple of problems with using nl, though, related to the desire to strip out the unwanted line numbers (even if you don't care about the aesthetics of it, there may be cases where using the extra columns would be undesirable). First, using "cut" to strip out the numbers re-introduces the buffering problem, so it wrecks the solution. Second, using "-w1" doesn't help, since this does NOT restrict the line number to a single column - it just gets wider as more digits are needed.

nl但是,使用 存在一些问题,与删除不需要的行号有关(即使您不关心它的美观,在某些情况下也可能不希望使用额外的列)。首先,使用“cut”去除数字重新引入了缓冲问题,因此它破坏了解决方案。其次,使用“-w1”没有帮助,因为这不会将行号限制为单列 - 随着需要更多数字,它只会变得更宽。

It isn't pretty if you want to capture this elsewhere, but since that's exactly what I didn't need to do (everything was being written to log files already, I just wanted to watch several at once in real time), the best way to lose the line numbers and have only my prefix was to start the -sstring with a carriage return (CR or ^M or Ctrl-M). So for example:

如果你想在别处捕捉它并不漂亮,但因为这正是我不需要做的(一切都已经被写入日志文件,我只想实时观看几个),最好的丢失行号并且只有我的前缀的方法是-s用回车符(CR 或 ^M 或 Ctrl-M)开始字符串。例如:

awk -v prefix="$prefix" '{print prefix 
$ cat /path/to/some/file | prefix_lines "WOW: "

WOW: some text
WOW: another line
WOW: more text
}' input_file.txt

回答by Melka

If your prefix is a bit complicated, just put it in a variable:

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

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 "" ]
then
  show_help
fi

# Check if input is from stdin or a file
FILE=
if [ -z "" ]
then
  # If no stdin exists
  if [ -t 0 ]; then
    show_help
  fi
  FILE=/dev/stdin
fi

# Now prefix the output
PREFIX=
sed -e "s/^/$PREFIX/" $FILE

Then, you pass that variable and let awk deal with it:

然后,您传递该变量并让 awk 处理它:

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

回答by Brad Parks

Here's a wrapped up example using the sedapproach from this answer:

这是使用此答案中sed方法的总结示例:

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

prefix_lines

前缀行

##代码##

回答by Benjamin W.

Using ed:

使用ed:

##代码##

This substitutes, for each line (,), the beginning of the line (^) with prefix. wqsaves and exits.

这种替代品,每行(,),行(年初^)用prefixwq保存并退出。

If the replacement string contains a slash, we can use a different delimiter for sinstead:

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

##代码##

I've quoted the here-doc delimiter EOE("end of ed") to prevent parameter expansion. In this example, it would work unquoted as well, but it's good practice to prevent surprises if you ever have a $in your ed script.

我引用了 here-doc 分隔符EOE(“end of ed”)以防止参数扩展。在这个例子中,它也可以不加引号地工作,但是如果你$的 ed 脚本中有 a ,那么防止意外是一种很好的做法。

回答by Ray

For people on BSD/OSX systems there's utility called lam, short for laminate. lam -s prefix filewill do what you want. I use it in pipelines, eg:

对于使用 BSD/OSX 系统的人来说,有一个实用程序叫做lam层压板的缩写。lam -s prefix file会做你想做的。我在管道中使用它,例如:

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

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

...which will find all files, exec lam on each of them, giving each file a prefix of its own filename. (And pump the output to fzf for searching.)

...它将找到所有文件,在每个文件上执行 lam,为每个文件提供其自己的文件名的前缀。(并将输出泵送到 fzf 进行搜索。)