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

发布于 2024-08-18 03:14:05 字数 255 浏览 7 评论 0原文

我有一个如下文件:

line1
line2
line3

我想得到:

prefixline1
prefixline2
prefixline3

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

前缀将包含/。它是一个路径,例如 /opt/workdir/

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

话少情深 2024-08-25 03:14:06

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

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

If you need to prepend a text at the beginning of each line that has a certain string, try following. In the following example, I am adding # at the beginning of each line that has the word "rock" in it.

sed -i -e 's/^.*rock.*/#&/' file_name
以往的大感动 2024-08-25 03:14:06

对于使用 BSD/OSX 系统的人来说,有一个名为 lam 的实用程序,它是“层压板”的缩写。 lam -s prefix file 将执行您想要的操作。我在管道中使用它,例如:

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

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

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

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.)

[浮城] 2024-08-25 03:14:06

另一种选择(海绵是可选的):

$ cat file | xargs -I{} echo 'prefix-{}-suffix' | sponge file

示例:

$ seq 1 10 | xargs -I{} echo 'prefix-{}-suffix'
prefix-1-suffix
prefix-2-suffix
prefix-3-suffix
prefix-4-suffix
prefix-5-suffix
prefix-6-suffix
prefix-7-suffix
prefix-8-suffix
prefix-9-suffix
prefix-10-suffix

Another alternative (sponge is optional):

$ cat file | xargs -I{} echo 'prefix-{}-suffix' | sponge file

Example:

$ seq 1 10 | xargs -I{} echo 'prefix-{}-suffix'
prefix-1-suffix
prefix-2-suffix
prefix-3-suffix
prefix-4-suffix
prefix-5-suffix
prefix-6-suffix
prefix-7-suffix
prefix-8-suffix
prefix-9-suffix
prefix-10-suffix
旧城空念 2024-08-25 03:14:06
SETLOCAL ENABLEDELAYEDEXPANSION

YourPrefix=blabla

YourPath=C:\path

for /f "tokens=*" %%a in (!YourPath!\longfile.csv)     do (echo !YourPrefix!%%a) >> !YourPath!\Archive\output.csv
SETLOCAL ENABLEDELAYEDEXPANSION

YourPrefix=blabla

YourPath=C:\path

for /f "tokens=*" %%a in (!YourPath!\longfile.csv)     do (echo !YourPrefix!%%a) >> !YourPath!\Archive\output.csv
顾忌 2024-08-25 03:14:05
# 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/'
# 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 prefix contains /, you can use any other character not in prefix, or
escape the /, so the sed command becomes

's#^#/opt/workdir#'
# or
's/^/\/opt\/workdir/'
梦里的微风 2024-08-25 03:14:05
awk '$0="prefix"$0' file > new_file

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

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

使用 Perl(就地替换):

perl -pi 's/^/prefix/' file
awk '$0="prefix"$0' file > new_file

In awk the default action is '{print $0}' (i.e. print the whole line), so the above is equivalent to:

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

With Perl (in place replacement):

perl -pi 's/^/prefix/' file
马蹄踏│碎落叶 2024-08-25 03:14:05

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

ex -sc '%s/^/prefix/|x' file
  1. % 选择所有行

  2. s 替换< /p>

  3. x 保存并关闭

You can use Vim in Ex mode:

ex -sc '%s/^/prefix/|x' file
  1. % select all lines

  2. s replace

  3. x save and close

青春如此纠结 2024-08-25 03:14:05

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

prefix=path/to/file/

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

awk -v prefix="$prefix" '{print prefix $0}' input_file.txt

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

prefix=path/to/file/

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

awk -v prefix="$prefix" '{print prefix $0}' input_file.txt
空城之時有危險 2024-08-25 03:14:05

这是使用 ts 来自 moreutils 的命令

$ cat file | ts prefix

以及它是如何逐步派生的:

# Step 1. create the file

$ cat file
line1
line2
line3
# Step 2. add prefix to the beginning of each line

$ cat file | ts prefix
prefix line1
prefix line2
prefix line3

请注意,前缀将与内容以空格分隔

Here is a oneliner solution using the ts command from moreutils

$ cat file | ts prefix

And how it's derived step by step:

# Step 1. create the file

$ cat file
line1
line2
line3
# Step 2. add prefix to the beginning of each line

$ cat file | ts prefix
prefix line1
prefix line2
prefix line3

Note that the prefix will be space separated from the content

谁的新欢旧爱 2024-08-25 03:14:05

如果你有 Perl:

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

If you have Perl:

perl -pe 's/^/PREFIX/' input.file
何以畏孤独 2024-08-25 03:14:05

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

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

或使用反向引用:

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

Using & (the whole part of the input that was matched by the pattern”):

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

OR using back references:

cat in.txt | sed -e "s/\(.*\)/prefix\1/" > out.txt
情绪少女 2024-08-25 03:14:05

使用外壳:

#!/bin/bash
prefix="something"
file="file"
while read -r line
do
 echo "${prefix}$line"
done <$file > newfile
mv newfile $file

Using the shell:

#!/bin/bash
prefix="something"
file="file"
while read -r line
do
 echo "${prefix}$line"
done <$file > newfile
mv newfile $file
血之狂魔 2024-08-25 03:14:05

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

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

不过,使用 nl 存在一些问题,这些问题与删除不需要的行号的愿望有关(即使您不关心它的美观,也可能在某些情况下使用额外的列是不可取的)。首先,使用“cut”删除数字会重新引入缓冲问题,因此破坏了解决方案。其次,使用“-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}

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.

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

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.

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 -s string with a carriage return (CR or ^M or Ctrl-M). So for example:

#!/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}
同展鸳鸯锦 2024-08-25 03:14:05

使用 ed:

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

对于每一行 (,),该行的开头 (^) 都替换为 前缀wq 保存并退出。

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

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

我引用了here-doc分隔符EOE(“end of ed”)来防止参数扩展。在此示例中,它也可以不加引号地工作,但如果您的 ed 脚本中有 $ ,那么最好的做法是防止出现意外。

Using ed:

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

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

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

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

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.

狂之美人 2024-08-25 03:14:05

这是使用此答案中的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

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

$ 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
荒人说梦 2024-08-25 03:14:05
  1. 您还可以使用反向引用技术来实现这一点

    sed -i.bak 's/\(.*\)/prefix\1/' foo.txt
    
  2. 您也可以像这样与 awk 一起使用

    awk '{print "prefix"$0}' foo.txt > tmp && mv tmp foo.txt
    
  1. You can also achieve this using the backreference technique

    sed -i.bak 's/\(.*\)/prefix\1/' foo.txt
    
  2. You can also use with awk like this

    awk '{print "prefix"$0}' foo.txt > tmp && mv tmp foo.txt
    
流绪微梦 2024-08-25 03:14:05

使用 Pythonize (pz):

pz '"preix"+s' <filename

Using Pythonize (pz):

pz '"preix"+s' <filename
暮年 2024-08-25 03:14:05

您可以使用 AWK

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

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

对于后缀:awk '{print $0"suffix"}'

对于前缀和后缀:awk '{print "prefix"$0 “后缀”}'

You can do it using AWK

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

or

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

For suffix: awk '{print $0"suffix"}'

For prefix and suffix: awk '{print "prefix"$0"suffix"}'

感受沵的脚步 2024-08-25 03:14:05

在 bash 命令行上使用 for 循环的简单解决方案:

for i in $(cat yourfile.txt); do echo "prefix$i"; done

将输出保存到文件中:

for i in $(cat yourfile.txt); do echo "prefix$i"; done > yourfilewithprefixes.txt

Simple solution using a for loop on the command line with bash:

for i in $(cat yourfile.txt); do echo "prefix$i"; done

Save the output to a file:

for i in $(cat yourfile.txt); do echo "prefix$i"; done > yourfilewithprefixes.txt
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文