简体   繁体   中英

Replace a line in a file using shell script

I need to replace a line in from a file using a shell script.

The file is:

# cat /root/sge_scripts/night_sched_conf
algorithm default
schedule_interval 0:0:05
maxujobs 12
queue_sort_method seqno

I want to replace the third line (after maxujobs) by a value generated in the script.

Here is what I have done so far:

#!/bin/sh
export SGE_ROOT=/opt/sge
source=/opt/sge/defalt/common/settings.sh
delete=1
total=`qstat -u "*" | awk ' { print $4 } ' | sort | uniq | wc -l`
total_users=$((total - delete))

case $total_users in

1) range=18;;
2) range=9 ;;
3) range=7 ;;
4) range=6 ;;
5) range=5 ;;
6) range=4 ;;
7) range=3 ;;
8) range=3 ;;
9) range=2 ;;
10) range=2 ;;
11) range=2 ;;
12) range=2 ;;
13) range=1 ;;
14) range=1 ;;
15) range=1 ;;
16) range=1 ;;
18) range=1 ;;
19) range=1 ;;
20) range=1 ;;
21) range=1 ;;
22) range=1 ;;
23) range=1 ;;
24) range=1 ;;
25) range=1 ;;
26) range=1 ;;
27) range=1 ;;
28) range=1 ;;
29) range=1 ;;
30) range=1 ;;
31) range=1 ;;
32) range=1 ;;
33) range=1 ;;
34) range=1 ;;
*) echo "INVALID NUMBER!" ;;
esac

current=`cat /root/sge_scripts/night_sched_conf | awk ' /maxujobs/ { print $2 } '`
if [ "$range" != "$current" ]
then
  sed -i '3s/.*/maxujobs           "$range"/' /root/sge_scripts/night_sched_conf
fi

Yes there is the way to do it .There is a command in linux called sed an stream editor which is used to edit the shell script files like updating the string or replace the string can be done in this.You could follow the below reference and try to replace.Try it out with this command and let me know if you are facing any issues

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM