
Chopping off the last field of each line?
I'm working on the Web site for Creating Cool Web Sites and just realized that the little Unix trick I used while editing a file is actually a beautiful example of why so many people love Unix so much, so I thought I'd share it. The problem: a file where lines have 1-10 words + a last field value (in this case, a page number) that I don't want. The challenge is to figure out how to easily remove that last field, when there are a variable number of fields on the line.
How does this work? The rev command reverses each line of input, so that means that the first field of each now-reversed line is the field that we want to remove. That's easily done with cut with the -f2- flag (that means output field two through the end of the line). Then, finally, we re-reverse (that is, fix) each line and save the output in a new file.$ rev inputfile | cut -f2- | rev > outputfile Quickly and easily done.
Help others find this article at Del.icio.us, Digg, Netscape, Reddit, and Stumble Upon
Categorized:
Unix and Linux Help
(Article 3690)
Tagged: Previous: How do I tweak my PATH? Next: Another nice review of Wicked Cool Shell Scripts Subscribe!
Never miss another useful Q&A article again! Subscribe to AskDaveTaylor with Google Reader. well done Posted by: pedestrian at August 19, 2007 9:20 AMtry this awk '{$NF=""; print $0}' Cheers I prefer: awk '{NF--;print}' With NF="" you will have additional spaces at the end of each line. Posted by: porges at March 5, 2009 7:50 AMNice, this just solved a problem I've been working on. So thanks. I figured I'd try to make it work without the rev. Reversing the argument of the -f parameter should returned the same results. Posted by: Cannon at February 13, 2010 2:07 PMI have something to say, now that you mention it, but ...
I do have a comment, now that you mention it!
|
![]()
Search
Find just the answers you seek from among our 2300+ free tech support articles by using our Lijit search engine.
Help!
Subscribe to
Ask Dave Taylor!
Free Updates!
Sign up and get free weekly updates and special offers on books, seminars, workshops and more.
Articles and Reviews
Auctions and Online Shopping Blogs and RSS Feeds Building Web site traffic Business and Management Cell Phones and Mobile Phones CGI Scripts and Web Site Programming Computer and Internet Basics d) None of the Above HTML and CSS Industry News and Trade Shows Mac OS X Help MySpace, Facebook, Twitter and Social Network Help Pay Per Click (PPC) Search Engine Optimization Shell Script Programming Sony PSP, MP3 Players, Etc. The Writing Business Unix and Linux Help Video Game Tips and Help Windows Help
Recent Entries
Book Links
|