Append text with AWK or SED?
Hi there,
I'm doing an assignment for school, and while we have not yet learned regular expressions, my teacher would like us to use AWK to append text to certain lines in a file. What we've had to do is creating a listing of all links and directories in the /etc folder and place them in a text file. From this, we were to cut the first field (Permissions) and the ninth field (filename) and create another text file. Now the part that I'm struggling with is this and I'm not sure if I should be using sed or awk. We're supposed to ADD the text "DIR" to the beginning of any line that is a directory, and "LNK" to any that is a link, like so: DIRdrwxr-xr-x redhat-lsb DIRdrwxr-xr-x rhgb LNKlrwxrwxrwx rnDIRc.key DIRdrwxr-xr-x rpm Obviously, I realize that the first character in the permissions denotes what sort of file it is, hence when I created my text file I used ls -l | grep "^d" > file.txt and ls -l | grep "^l" >> file.txt I'd like to learn how to properly do this, but struggling through pages on the internet hasn't been helping, nor has the --help command. Therefore, while I would like the answer, I'd also like to know what the heck I'm doing :) For example, I know I could delete lines with regex using d/[STUFF I WANT TO DELETE]/g (To get rid of all occurences) and I can substitute using s/foo/bar But I'm unaware of anyway to ADD text upon certain occurences, let alone two different circumstances. Thank you! |
i would use sed to substitute.
whats the difference between a substitute and an append ? |
Just to expand on that a little why not substitute "DIRd" in place of "d" ?. Using the appropriate anchor of course.
I too would use sed for this, but awk will do too - as will perl or python or ... |
A couple hints, since this is homework. In sed and awk, use /<pattern>/ to select lines you want to work with.
In sed, read the man page for that '&' means. In awk, look in the info or man page for $0. Also learn how to negate a match in awk. |
Quote:
syg00, I followed your logic (I can't believe I didn't think of that. I was so focused on trying to append :P) and it worked like a charm. I used two seperate sed commands in order to substitute the appropriate text for each case (l and d) jschiwal, I read the man page, and spotted the & symbol as you suggested but the explanation escaped me... :( Code:
s/regexp/replacement/ |
You can combine the two into one
Code:
sed -e '<first substitution>' -e '<next substitution>' ... |
Quote:
|
All times are GMT -5. The time now is 12:09 AM. |