Reputation: 9
I want a Bash script that puts userinput
into a file called software.txt
. But I need the userinput
to be under a specific line #addedsoftware
in software.txt
. The script should be able to add useriput
multiple times into this file. Is this something that can be achieved with something like sed
?
When i ran sed '/#TESTING/a some text here' software.txt
it did not add it to the file. Then i ran sed '/#TESTING/a some text here' > software.txt
This one just adds whatever keys i press after the command is ran.
Edit i got it working with.: sed -i '/#TESTING/a some text here' file
Upvotes: 0
Views: 1142
Reputation: 69
Would something like this work? It takes the software.txt
file and splits it into two parts, top and bottom. Top is everything up to the specified line and bottom is everything after that line. Then it puts the software.txt
file back together with the user input between the two parts.
For example say your software.txt file looks like this.
software.txt
# Software.txt
Line 3
Line 4
Line 4
Line 6
# Put user input below this line.
Line 10
Line 11
Line 12
insert_user_input.sh
#!/usr/bin/env bash
# Read user input.
echo -n "Enter input: "
read user_input
software_txt_top_half=$(sed '/# Put user input below this line./q' software.txt)
software_txt_bottom_half=$(sed '1,/# Put user input below/d' software.txt)
# Insert user input into software.txt after specified line.
cat << EOF > software.txt
$software_txt_top_half
$user_input
$software_txt_bottom_half
EOF
Then after running the script it would look like this,
$ ./insert_user_input.sh
Enter input: asdfasdfasdfasdfasdfasdf
# Software.txt
Line 3
Line 4
Line 4
Line 6
# Put user input below this line.
asdfasdfasdfasdfasdfasdf
Line 10
Line 11
Line 12
Upvotes: 1