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:10

I'd recommend defining a function and then importing and using that where needed.

prepend_to_file() { 
    file=$1
    text=$2

    if ! [[ -f $file ]] then
        touch $file
    fi

    echo "$text" | cat - $file > $file.new

    mv -f $file.new $file
}

Then use it like so:

prepend_to_file test.txt "This is first"
prepend_to_file test.txt "This is second"

Your file contents will then be:

This is second
This is first

I'm about to use this approach for implementing a change log updater.

查看更多
Emotional °昔
3楼-- · 2019-01-13 00:11

Solution:

printf '%s\n%s' 'text to prepend' "$(cat file.txt)" > file.txt

Note that this is safe on all kind of inputs, because there are no expansions. For example, if you want to prepend !@#$%^&*()ugly text\n\t\n, it will just work:

printf '%s\n%s' '!@#$%^&*()ugly text\n\t\n' "$(cat file.txt)" > file.txt

The last part left for consideration is whitespace removal at end of file during command substitution "$(cat file.txt)". All work-arounds for this are relatively complex. If you want to preserve newlines at end of file.txt, see this: https://stackoverflow.com/a/22607352/1091436

查看更多
我只想做你的唯一
4楼-- · 2019-01-13 00:11

If you like vi/vim, this may be more your style.

printf '0i\n%s\n.\nwq\n' prepend-text | ed file
查看更多
别忘想泡老子
5楼-- · 2019-01-13 00:13

Probably nothing built-in, but you could write your own pretty easily, like this:

#!/bin/bash
echo -n "$1" > /tmp/tmpfile.$$
cat "$2" >> /tmp/tmpfile.$$
mv /tmp/tmpfile.$$ "$2"

Something like that at least...

查看更多
在下西门庆
6楼-- · 2019-01-13 00:15

Another fairly straight forward solution is:

    $ echo -e "string\n" $(cat file)
查看更多
太酷不给撩
7楼-- · 2019-01-13 00:17

Process Substitution

I'm surprised no one mentioned this.

cat <(echo "before") text.txt > newfile.txt

which is arguably more natural than the accepted answer (printing something and piping it into a substitution command is lexicographically counter-intuitive).

...and hijacking what ryan said above, with sponge you don't need a temporary file:

sudo apt-get install moreutils
<<(echo "to be prepended") < text.txt | sponge text.txt

EDIT: Looks like this doesn't work in Bourne Shell /bin/sh


Here String

Using a here-string - <<< (again, you need bash), you can do:

<<< "to be prepended" < text.txt | sponge text.txt
查看更多
登录 后发表回答