The following is a "safe" use of a tmp file - the && only on success will continue with the following command, and the cp leaves the inode/owner/group/permissions/linkage intact.
Your Welcome. On unix.com we Thank people for useful posts by hitting THANKS button at each post's last left side, you could do so too, cheers and happy learning.
Also don't forget to put code tags for your samples/codes too.
Below I am hard-coding the value of line number .How to pass it with variable ?
In my script (Solaris) say in abc.txt ,it's 3rd line I have to comment
sed '3s/^/#/' abc.txt > temp && mv temp abc.txt
cat abc.txt
bc
vdv
shhsd
cdc
skdk
Script
#!/bin/bash
#set -x
grep -n cdc abc.txt | cut -f1 -d: | sort -u >>a.txt
filename="a.txt"
while read line
do
# $line variable contains current line read from the file
# display $line text on the screen or do something with it.
echo "$line"
sed $lines^/#/" abc.txt > temp && mv temp abc.txt
done < $filename
A bit complex, no? And a waste of resources, if you change more than one line, as you open/read your file, create a temp file, and mv it once per change!
If you know the pattern, why the detour via grep (and the needless sort )? Why not have sed do it all for you, like
sed '/cdc/s/^/#/' file
? That will comment out any line that has cdc in it, at any position. Anchor the pattern at begin-of-line with ^ , if need be.
For your syntax problem (I presume you have, but you don't post any error message), use a leading double quote, and enclose the variable name in braces. man bash :
tried executing your command in SOLARIS but end-up with below
bash-3.2$
sed -n '/cdc/=' abc.txt | sed 's-$-s/^/#/-' | sed -f- abc.txt
Cannot open pattern-file: -
My requirement is as below.
i have to check for any entry say cdc in a file abc.txt and from their i will comment the one which i need.
Example
I am getting the line numbers where cdc occurred ,as below and i am interested in commenting line 2 and 7 only not 5 in single go by passing the line numbers i have to comment it,Please suggest how this can be done in Solaris or do you have any other approach,kindly suggest
That means you need to interact with the script to select / deselect the relevant lines. Which would make your approach in post #6 moot. You'd need to find the lines, propose them to the user, read the y/n answer, and then go on commenting them out.
Need help on below code, where i am trying to redirect the output of grep command in a file /tmp/a.txt for each server with this below code but it's only getting generated on server1 why not in server2 and 3 ? please advise
Always try to following rule of 1 thread ==> 1 question please.
Geeks have really helped you in this thread, so for future users who want to get reference from this thread, will get confuse if you keep adding questions to a same post, kindly keep post's Original question ALIVE through out the threads and open new threads for new questions, cheers and happy learning on this GREAT forum UNIX.com