0

I need to write shell script to create a new file and insert some stuffs into it. The problem is, using sed 'i/blablabla' command, it only works when there is at least one line existed in the file. What is the command to insert into a new file?

Thanks

1
  • do you actually need to edit the stream (do some find/replacement in the text) before you write it to the file? Commented Mar 12, 2012 at 18:41

3 Answers 3

2
echo 'new line' >file_name

Also, you can append to the end without using sed using the >> operator:

echo 'additional line' >>file_name
Sign up to request clarification or add additional context in comments.

2 Comments

Really appreciated. So sed could not be applied in this case?
sed could be used, but there's no need for it -- sed is for editing streams; editing implies starting with something and changing it; you're not doing that, so just using functionality built into the shell instead of starting a separate tool (such as sed) makes more sense.
1

More variants:

cat >>file_being_appended_to <<some_random_string
This is the first line
This is the second line and it has a variable in it; it's right here: $some_variable
some_random_string
cat >>file_being_appended_to <<'some_random_string'
This is the first line
This is the second line and it has a variable reference in it; it's right here: $some_variable,
but this variable reference is not expanded because the beginning delimiter string has single quotes around it.
some_random_string

1 Comment

Use vi? :) Seriously, I think you meant "If i want to write a script to add a line to middle of file, what shoud i do???"? (line_number=40; sed "$line_number,\$d" your_file; ((line_number--)); echo "stuff you want inserted";sed "1,${line_number}d" your_file) >your_new_file The first sed prints out the first part of the file; the second sed prints out the second part of the file.
0

Other variants:

echo 'This is the first line
This is the second line.' >file
some_variable="some value"
echo "This is the first line
This is the second line and it has a variable in it; it's right here: $some_variable" >file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.