سؤال

How can I write text to a file using sed? More specifically I would it add null variables to my blank text file that was created using touch. The syntax of sed is very confusing to me.

هل كانت مفيدة؟

المحلول 2

If you're just appending text to the end of the file then you wouldn't use sed in the first place.

echo "some text" >> somefile.txt

نصائح أخرى

Use $ a.

sed -i "$ a some text" somefile.txt

Adding a late post because while the accepted answer is the simplest solution to this problem, the question actually highlights a couple of common situations:

  1. Need to edit a file via sudo
  2. Trying to use sed to modify an empty file.

In short, you can't touch, then edit a file with sed. Sed doesn't work on empty files, but occasionally you need to do the equivalent of

sudo echo "some text" >> somefile.txt

sudo doesn't like the redirect, but there are workarounds:

echo "some text" | sudo tee --append somefile.txt

or if pipes are not an option either, or you simply must use sed, or you just like complexity:

dd if=/dev/zero count=1 bs=1 of=somefile.txt
sed -i '$ a some text' somefile.txt
sed -i '1 d' somefile

On some systems,. you might have to use sed -i -e '$ a ...

This sounds like an XY Problem to me. You might get better or more useful answers if you ask about what problem you're trying to solve, rather than asking for help implementing a particular solution.

But if you absolutely must do this in sed, you can use sed's r command to read a file. For example:

[ghoti@pc ~/tmp]$ cat one
RED
BLUE
[ghoti@pc ~/tmp]$ cat two
green
yellow
[ghoti@pc ~/tmp]$ echo ">> start"; sed '$r two' one; echo ">> end"
>> start
RED
BLUE
green
yellow
>> end
[ghoti@pc ~/tmp]$ 

The sed command $r two causes sed to slurp in the file named "two" after processing the last line of input (which in this case is from the file "one").

Note that this merges one file into the stream of another file, but sed's "standard output" (stdout) is what contains the full/combined stream. You can redirect that output to a file per Ignacio's answer if that's what you want.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top