Unix command to prepend text to a file

2019-01-12 23:44发布

Is there a Unix command to prepend some string data to a text file?

Something like:

prepend "to be prepended" text.txt

16条回答
成全新的幸福
2楼-- · 2019-01-13 00:20

This will work to form the output. The - means standard input, which is provide via the pipe from echo.

echo -e "to be prepended \n another line" | cat - text.txt

To rewrite the file a temporary file is required as cannot pipe back into the input file.

echo "to be prepended" | cat - text.txt > text.txt.tmp
mv text.txt.tmp text.txt
查看更多
一夜七次
3楼-- · 2019-01-13 00:21

Prefer Adam's answer

We can make it easier to use sponge. Now we don't need to create a temporary file and rename it by

echo -e "to be prepended \n another line" | cat - text.txt | sponge text.txt
查看更多
爷、活的狠高调
4楼-- · 2019-01-13 00:24

Another way using sed:

sed -i.old '1 {i to be prepended
}' inFile

If the line to be prepended is multiline:

sed -i.old '1 {i\ 
to be prepended\
multiline
}' inFile
查看更多
再贱就再见
5楼-- · 2019-01-13 00:27

If it's acceptable to replace the input file:

Note: Doing so may have unexpected side effects, notably replacing a symlink with a regular file, possibly ending up with different permissions on the file, and changing the file's creation (birth) date.

sed -i, as in Prince John Wesley's answer, tries to at least restore the original permissions, but the other limitations apply.

 { printf 'line 1\nline 2\n'; cat text.txt; } > tmp.txt && mv tmp.txt text.txt

Note: Using a group command { ...; ... } is more efficient than using a subshell ((...; ...)).


If the input file should be edited in place (preserving its inode with all its attributes):

Using the venerable ed POSIX utility:

Note: ed invariably reads the input file as a whole into memory first.

ed -s text.txt <<'EOF' 
1i
line 1
line 2
.
w
EOF
  • -s suppressed ed's status messages.
  • Note how the commands are provided to ed as a multi-line here-document (<<'EOF' ... EOF), i.e., via stdin.
  • 1i makes 1 (the 1st line) the current line and starts insert mode (i).
  • The following lines are the text to insert before the current line, terminated with . on its own line.
  • w writes the result back to the input file (for testing, replace w with ,p to only print the result, without modifying the input file).
查看更多
唯我独甜
6楼-- · 2019-01-13 00:28
# create a file with content..
echo foo > /tmp/foo
# prepend a line containing "jim" to the file
sed -i "1s/^/jim\n/" /tmp/foo
# verify the content of the file has the new line prepened to it
cat /tmp/foo
查看更多
神经病院院长
7楼-- · 2019-01-13 00:29
sed -i.old '1s;^;to be prepended;' inFile
  • -i writes the change in place and take a backup if any extension is given. (In this case, .old)
  • 1s;^;to be prepended; substitutes the beginning of the first line by the given replacement string, using ; as a command delimiter.
查看更多
登录 后发表回答