Linux 如何在文件开头插入文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9533679/
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-06 04:57:00  来源:igfitidea点击:

How to insert a text at the beginning of a file?

linuxbashsed

提问by user219882

So far I've been able to find how to add a line at the beginning of a file but that's not exactly what I want. I'll show it on a example

到目前为止,我已经能够找到如何在文件开头添加一行,但这并不是我想要的。我会在一个例子中展示它

File content

文件内容

some text at the beginning

Result

结果

<added text> some text at the beginning

It's similar but I don't want to create any new line with it...

它很相似,但我不想用它创建任何新行...

I would like to do this with sedif possible.

sed如果可能的话,我想这样做。

采纳答案by kev

sedcan operate on an address:

sed可以对地址进行操作:

$ sed -i '1s/^/<added text> /' file

What is this magical 1syou see on every answer here? Line addressing!.

1s您在此处的每个答案中看到的神奇之处是什么?线路寻址!.

Want to add <added text>on the first 10 lines?

想要添加<added text>前 10 行吗?

$ sed -i '1,10s/^/<added text> /' file

Or you can use Command Grouping:

或者你可以使用Command Grouping

$ { echo -n '<added text> '; cat file; } >file.new
$ mv file{.new,}

回答by paxdiablo

If the file is only one line, you can use:

如果文件只有一行,可以使用:

sed 's/^/insert this /' oldfile > newfile

If it's more than one line. one of:

如果不止一行。之一:

sed '1s/^/insert this /' oldfile > newfile
sed '1,1s/^/insert this /' oldfile > newfile

I've included the latter so that you know how to do ranges of lines. Both of these "replace" the start line marker on their affected lines with the text you want to insert. You can also (assuming your sedis modern enough) use:

我已经包含了后者,以便您知道如何处理行范围。这两者都用您要插入的文本“替换”受影响行上的起始行标记。您还可以(假设您sed足够现代)使用:

sed -i 'whatever command you choose' filename

to do in-place editing.

进行就地编辑。

回答by xck

Hi with carriage return:

你好,回车:

sed -i '1s/^/your text\n/' file

回答by Ali Reza Ebadat

If you want to add a line at the beginning of a file, you need to add \nat the end of the string in the best solution above.

如果要在文件开头添加一行,则需要\n在上述最佳解决方案中的字符串末尾添加。

The best solution will add the string, but with the string, it will not add a line at the end of a file.

最好的解决方案是添加字符串,但对于字符串,它不会在文件末尾添加一行。

sed -i '1s/^/your text\n/' file

回答by Lex

You can use cat -

您可以使用 cat -

printf '%s' "some text at the beginning" | cat - filename

回答by paulp

echo -n "text to insert " ;tac filename.txt| tac > newfilename.txt

The first tacpipes the file backwards (last line first) so the "text to insert" appears last. The 2nd tacwraps it once again so the inserted line is at the beginning and the original file is in its original order.

第一个tac管道向后传输文件(最后一行在前),因此“要插入的文本”出现在最后。第二个tac再次包装它,因此插入的行位于开头,原始文件以其原始顺序排列。

回答by Curt Clifton

Note that on OS X, sed -i <pattern> file, fails. However, if you provide a backup extension, sed -i old <pattern> file, then fileis modified in place while file.oldis created. You can then delete file.oldin your script.

请注意,在 OS X 上,sed -i <pattern> file, 失败。但是,如果您提供备份扩展名sed -i old <pattern> file,则filefile.old创建时就地修改。然后您可以file.old在脚本中删除。

回答by Curt Clifton

To insert just a newline:

只插入一个换行符:

sed '1i\'

回答by solidsnack

To add a line to the top of the file:

在文件顶部添加一行:

sed -i '1iText to add\'

回答by Victoria Stuart

PROBLEM:tag a file, at the top of the file, with the base name of the parent directory.

问题:使用父目录的基本名称在文件顶部标记文件。

I.e., for

即,对于

/mnt/Vancouver/Programming/file1

tag the top of file1with Programming.

标签的顶部file1Programming

SOLUTION 1-- non-empty files:

解决方案 1-- 非空文件:

bn=${PWD##*/}    ## bn: basename

sed -i '1s/^/'"$bn"'\n/' <file>

1splaces the text at line 1 of the file.

1s将文本放在文件的第 1 行。

SOLUTION 2-- empty or non-empty files:

解决方案 2——空或非空文件:

The sedcommand, above, fails on empty files. Here is a solution, based on https://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in-bash/246841#246841

sed上面的命令在空文件上失败。这是一个解决方案,基于https://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in-bash/246841#246841

printf "${PWD##*/}\n" | cat - <file> > temp && mv -f temp <file>

Note that the -in the cat command is required (reads standard input: see man catfor more information). Here, I believe, it's needed to take the output of the printf statement (to STDIN), and cat that and the file to temp ... See also the explanation at the bottom of http://www.linfo.org/cat.html.

请注意,需要-in cat 命令(读取标准输入:man cat有关更多信息,请参阅)。在这里,我相信,需要获取 printf 语句的输出(到 STDIN),并将该文件和文件放入 temp ......另见http://www.linfo.org/cat底部的解释html的

I also added -fto the mvcommand, to avoid being asked for confirmations when overwriting files.

我还添加-fmv命令中,以避免在覆盖文件时要求确认。

To recurse over a directory:

要递归目录:

for file in *; do printf "${PWD##*/}\n" | cat - $file > temp && mv -f temp $file; done

Note also that this will break over paths with spaces; there are solutions, elsewhere (e.g. file globbing, or find . -type f ...-type solutions) for those.

另请注意,这将中断带有空格的路径;其他地方有解决方案(例如文件通配或find . -type f ...-type 解决方案)。

ADDENDUM:Re: my last comment, this script will allow you to recurse over directories with spaces in the paths:

附录:回复:我的最后一条评论,此脚本将允许您递归路径中带有空格的目录:

#!/bin/bash

## https://stackoverflow.com/questions/4638874/how-to-loop-through-a-directory-recursively-to-delete-files-with-certain-extensi

## To allow spaces in filenames,
##   at the top of the script include: IFS=$'\n'; set -f
##   at the end of the script include: unset IFS; set +f

IFS=$'\n'; set -f

# ----------------------------------------------------------------------------
# SET PATHS:

IN="/mnt/Vancouver/Programming/data/claws-test/corpus test/"

# https://superuser.com/questions/716001/how-can-i-get-files-with-numeric-names-using-ls-command

# FILES=$(find $IN -type f -regex ".*/[0-9]*")        ## recursive; numeric filenames only
FILES=$(find $IN -type f -regex ".*/[0-9 ]*")         ## recursive; numeric filenames only (may include spaces)

# echo '$FILES:'                                      ## single-quoted, (literally) prints: $FILES:
# echo "$FILES"                                       ## double-quoted, prints path/, filename (one per line)

# ----------------------------------------------------------------------------
# MAIN LOOP:

for f in $FILES
do

  # Tag top of file with basename of current dir:
  printf "[top] Tag: ${PWD##*/}\n\n" | cat - $f > temp && mv -f temp $f

  # Tag bottom of file with basename of current dir:
  printf "\n[bottom] Tag: ${PWD##*/}\n" >> $f
done

unset IFS; set +f