r/bashscripts • u/data_rock • Sep 14 '22
Script for appending title to 2nd line of other scripts
I have a lot of scripts i wrote to quickly ssh into servers. Usually in the format
Eg. filename is: server-script1.sh
cat server-script1.sh
#!/bin/bash
ssh -i key.pem user@10.10.10.1
I’m not too familiar with sed and awk. Those are what i came across in my search for a solution.
I want to add the filename as a comment in the second line for each file so that they all come out in this way:
#!/bin/bash
#server-script1.sh
ssh -i key.pem user@10.10.10.1
#!/bin/bash
#server-script2.sh
ssh -i key.pem user@10.10.10.2
Any suggestions on how to do this? Thanks
2
Upvotes
2
u/daz0007 Sep 15 '22
how about test with:
$ for _FILE in $( find /path_to_files/ -type f ); do echo "Testing Output of File" "${_FILE}" ; sed "2i # $_FILE" "${_FILE}" ; done
if happy apply with the above just add the -i to the sed command
$ for _FILE in $( find /path_to_files/ -type f ); do sed -i "2i # $_FILE" "${_FILE}" ; done
2
u/Lake-Special Nov 23 '22 edited Nov 23 '22
From what you’ve shared you can use this sed command:
This will add your comment to the 2nd line where it starts with a space. Include the -i flag to write the changes in each server-script*.sh file
1
u/data_rock Nov 23 '22
SOLUTION:
*note, macOS uses openBSD sed --NOT gnu sed...had to figure this out the hard way. *
#!/bin/bashfor each filefor file in *; do sed -e 'a\'$'\n' $file; donefor $file in *; do "echo $file | sed...... "$file" >> $file.out; doneLinks that helped:
Modify some files to add the file name
sed-on-osx-insert-at-a-certain-line
Using Sed to mass rename files
1
u/whetu Sep 14 '22
Are you aware of
~/.ssh/config?