Answers to #1 and #2.
Use awk to parse through lines of a text file. This can be used to trim the end off of lines as well as break up the line into pieces and get only the ones you want.
The basic way to interface a file with awk is this:
Code:
awk 'pattern {action}' filename
For instance, by leaving pattern blank and specifying an action to print out the line, awk will go through each line and print it out. Like this:
Code:
awk '{print $0}' testfile
To put the output of this command into a new file, just redirect it with the > character. Like this:
Code:
awk '{print $0}' testfile > resultfile
The previous command essentially copies each line of testfile into resultfile performing a filesystem copy.
---------------------------------------------------
For #1:
Just print out each line, minus the last character. Like this:
Code:
awk '{print substr($0, 1, length-1)}' testfile > resultfile
resultfile will contain the results of taking the last character off of each line. Use length-2 to take the last two characters off of eachline.
You can also test to see if the last character in the line is a space, so it wouldn't take a character off the end of a line ending in 'g' for example. Use this for your action:
Code:
'{if(substr($0,length,length)==" ") print substr($0,1,length-1); else print $0;}'
This will only strip the last character of a line if the last character is a space.
---------------------------------------------------
For #2
awk also breaks lines into pieces. By default, it breaks up the line by spaces. In the line 'This rocks!', awk would break it into two pieces.
To get the different pieces you want, use $1 where 1 is the piece number you want to access. $0 means the whole line (we used that in earlier examples). For an enxample:
Code:
awk '{print $1, $3}' testfile
This would print the first and third word of every line.
To specify what character to use as the delimiter, use the -F option. Like this:
Code:
awk -F ',' '{print $1, substr($3, 1, 3)}' testfile
This example would print the first element and the first three characters of the third element in each line where the elements are separated by a comma.
---------------------------------------------
Final note:
You can use the output of other commands on the commandline as the input to awk. For example you can pipe the output of a process listing to awk like this:
Code:
ps -ef | awk '{print $8}'
This example prints off the name of every process currently running.
---------------------------------------------
Quiz!!!
Can anyone come up with a way to kill any current more process using a combination of kill, ps, and awk??
To test out your answer, open a terminal window and cd to directory with text file in it. Type 'more textfile'. Now open another terminal window and run your kill, ps, awk script. Does it work??
I hope this quick guide to awk helps. Now I can say I was somewhat productive this Saturday.
Taft