Awk with spaces?
December 1, 2007 4:48 PM   Subscribe

Help with awk - printing everything EXCEPT the first column?

I have a tool that we'll call "junk", which prints out a line per file, each line starting with junk that I'm not interested in (in a single column), followed by the name of the file, which I am interested in. For example:

$ junk
junk SomeFile.txt
crap SomeOtherFile.txt
stuff AThirdFile.txt

I can usually get what I'm interested in via a simple pipe to awk:

$ junk | awk '{print $2}'
SomeFile.txt
SomeOtherFile.txt
AThirdFile.txt

But consider the following:

$ junk
junk SomeFile.txt
crap SomeOtherFile.txt
stuff AThirdFile.txt
rubbish A File Containing Spaces In Its Name.txt

$ junk | awk '{print $2}'
SomeFile.txt
SomeOtherFile.txt
AThirdFile.txt
A

Now, of course I can do something like the following:

$ junk | awk '{print $2, $3, $4, $5, $6, $7, $8}'

But that has (at least) the following problems:
  • It doesn't correctly handle files with multiple consecutive spaces in the filenames
  • Nor filenames that start or end with spaces
  • I have to make sure that I typed in enough $x variables to fit the filenames in question
  • It's annoying to type
Surely there must be a better way. What is it?

To be clear, I am not wed to awk. If there's another tool that does what I want, great. And if there's an easy way to get close to what I want (for example, forgetting about the possibility of spaces at the start and end of a filename), that's good too.

Thanks.
posted by Flunkie to Computers & Internet (7 answers total)
 
Best answer: Ugly:
junk | awk '{ print substr($0, index($0, " ")); }'

Less ugly:

junk | cut -d' ' -f2-
posted by sergent at 5:03 PM on December 1, 2007 [1 favorite]


Best answer: try cut -f2- -d" "
posted by philomathoholic at 5:04 PM on December 1, 2007


Can you use perl? That replaces a lot of the stuff you'd do with sed/awk.

Here's a command-line statement that will do what you want (one line, in case there are breaks when Ask MeFi posts it):

$ junk | perl -e 'while (<>) { ($junk, $filename) = split(/ /,$_,2); print "$filename\n"; } '
posted by chengjih at 5:04 PM on December 1, 2007


Will the first column always terminate with a single space character? If so, you could use a perl regular expression to strip it away:

junk | perl -pe 's/^\w+\s//g'
posted by ijoshua at 5:04 PM on December 1, 2007


Response by poster: Excellent. Thanks!
posted by Flunkie at 5:07 PM on December 1, 2007


Or, for that matter

junk | sed 's/^[^ ]* //'

which is basically the equivalent of ijoshua's 'perl -pe' version.
posted by hattifattener at 5:27 PM on December 1, 2007



junk | awk '{for(i=2;i<=NF;i++){printf $i " "};print}'

posted by [@I][:+:][@I] at 7:19 AM on December 3, 2007


« Older What are some good Christmas movies?   |   How to transform my husband for <$1000? Newer »
This thread is closed to new comments.