Bash & sed question
Hi All!
I write a script that replace some lines following a pattern, using 'sed'. The script works fine, but now i need to update it to replace only the last occurrence of that pattern en the file. For example: #a user user= foo name= John password= 2312 #another user user= tiger name= Will password= 5887 Im searching by the pattern '^user= '. There is any way to replace ONLY the last occurrence of the pattern? Thanks! |
Hm, I'm sure that in any language You would have to loop through the occurences of ^user and save it in a list/array. Sed has that capability too. The last one received is the one You want to replace. But I couldn't help it, here's one in bash/sed that does the same thing. This is not a help with sed. But I think it illustrates what You want to do and the benefits of the *nix toolbox... I assume the file has a list of records where user is unique, and also that You separate the name with space before it, like:
lakris@ubuntu:~$ cat users.txt #a user user= foo name= John password= 2312 #another user user= tiger name= Will password= 5887 lakris@ubuntu:~$ new=lion;org=`cat users.txt |grep ^user|tail -1|cut -d" " -f2`;cat users.txt|sed -e "s/^user=\ $org/user=\ $new/" #a user user= foo name= John password= 2312 #another user user= lion name= Will password= 5887 lakris@ubuntu:~$ of course You could redirect it and do some file renaming and stuff to update the actual "database". lion could be Your input to a script, even the file name. Excercise left to reader... |
Quote:
Code:
ex - infile<<! |
in awk
Code:
awk 'FNR==NR{ if ($0 ~ /^user=/ ){ Code:
# ./test1.sh |
Thanks to AL!!!
specially to lakris, your answer is clear and works ok! Im a begginer in the bash world and there are several commands that i dont know (i.e: tail, cut, head) where can i found a list (or a reference) of that commands and what each do? Again, THANKS TO ALL!!!! PD: Sorry my gad english |
Quote:
I have found this, http://www.tldp.org/LDP/abs/html/ , to be a very good resource on bash (and the site http://www.tldp.org/ for most GNU/Linux tools). And of course, man tail, etc is a good way to start. Your distro may have additional documentation packages with HOWTO's and coding examples. A very good way to start is to look at how others solved a specific or similar problem. I often find myself whipping up one-liners where others would turn to perl or even a higher level programming language. bash and friends are really powerful, fast and intuitive. Happy hackin'! /Lakris |
I recently wrote a pretty complex name parser using cat, echo, cut, tr, rev, head, tail and grep.
|
Quote:
Code:
perl -e 'print "hello world\n";' |
Quote:
Code:
cat file | grep "blah" |
All times are GMT -5. The time now is 06:37 PM. |