如何在文件的第一行添加新的文本行?

Nai*_*ita 2 sed awk text-processing

文件:

TABLE1

1234 
9555    
87676  
2344
Run Code Online (Sandbox Code Playgroud)

预期输出:

Description of the following table:
TABLE1

1234
9555
87676
2344
Run Code Online (Sandbox Code Playgroud)

Aar*_*ron 9

实际上echo并且cat足以做你想做的事:

echo "Description of the following table:" | cat - file
Run Code Online (Sandbox Code Playgroud)

-参数告诉cat从中读取数据stdin


cuo*_*glm 7

sed

$ sed -e '1i\
Description of the following table:
' <file
Description of the following table:
TABLE1

1234
9555
87676
2344
Run Code Online (Sandbox Code Playgroud)


cas*_*cas 5

printf "%s\n" 1 i "Description of the following table:" . w | ed filename
Run Code Online (Sandbox Code Playgroud)

printf输出ed命令(每行一个),其然后管道输送到ed filename

ed 按照说明编辑文件:

1                                        # go to line 1
i                                        # enter insert mode
Description of the following table:      # text to insert
.                                        # end insert mode
w                                        # write file to disk
Run Code Online (Sandbox Code Playgroud)

顺便说一句,ed执行真正的就地编辑,而不是像sed大多数其他文本编辑工具那样写入临时文件并移动。编辑后的文件在文件系统中保持相同的 inode。