On Friday 30 January 2004 16:17, Ben Yau wrote:
(grep year7 passwd | awk -F: '{print "mv /home/"$1" /home/year7/"$1}') | cat
This will print out what the script is going to do. If it
looks good, you
can then redirect to a file and run as a shell script OR change "cat" to "/bin/sh" or "/bin/bash" and it will then do the actual "mv "commands.
Ben
Hi and thanks for the tips. I changed it to:
(grep year7 /etc/passwd | awk -F: '{print "mv /home/"$1" /home/year7/"$1}') | cat
Good idea on the "/etc/passwd". Not a quick one liner explanation, but here is a brief explanation. If you do a man on grep and awk, you will get the complete info . The short version is:
grep searchstring file
will look in "file" and print out every line that has searchstring in it. There are a lot of args you can use (case sensitive, etc.).
The | is a pipe . It will use the standard output of the previous command as standard input of the next command
awk '{print $1}'
on it's own will print out the first column of the output using whitespace as a delimiter. to print out the second column, use $2, third column $3, and last column $NF. I usually use awk as part of a pipe. For example:
# echo "col1 col2 col3" | awk '{print $1}' col1 # echo "col1 col2 col3" | awk '{print $2}' col2 # echo "col1 col2 col3" | awk '{print $NF}' col3 #
To change the delimiter from white space to something else, use -F option followed by the character you want as a delimiter. In the case of /etc/passwd, we want to use the colon as the delimiter. Try the below to see what you get.
cat /etc/passwd | awk -F: '{print $1}' cat /etc/passwd | awk -F: '{print $2}' cat /etc/passwd | awk -F: '{print $NF}'
(Note: similar to how you can specify a filename in the "grep" command, you can do the same thing with awk. cat /etc/passwd | awk -F: '{print $1}'
and
awk -F: '{print $1}' /etc/passwd
will give the same results.
Now the print utility is very strong in awk. You can specify other strings to print out literally with the double quote. Anything in double quotes is printed out. So you can print out
echo "file1 file2" | awk '{print "mv "$1" to "$file2}'
The trickiest part of awk and printing is keeping track of your double quotes. That's the basics.
Hope that helps.
Utterly and 100%'ly. You guys have saved me so much time. Next round on me. Cheers, Steve.