gawk gets fixed width field

ls -l | gawk -v FIELDWIDTHS='1 3 3 3' '{print $2}'

5
By: kev
2012-02-08 08:18:25

These Might Interest You

  • Use tput cols to find the width of the terminal and set it as the minimum field width. Show Sample Output


    9
    printf "%$(tput cols)s\n"|tr ' ' '='
    webstandardcss · 2012-04-21 23:26:55 1
  • only take the first field on each row to compute the fibo on this number Show Sample Output


    -5
    gawk '{n=$1;a=0;b=1;c=1;for(i=1;i<n;i++){c=a+b;a=b;b=c};print c}' << eof
    unixmonkey13930 · 2010-11-26 08:36:30 0
  • The $2, $3, $4 fields are arbitrary but note that the first field starts from $2 and the last field is $NF-1. This is due to the fact that the leading and trailing quotes are treated as field delimiters. Show Sample Output


    7
    awk -F'^"|", "|"$' '{ print $2,$3,$4 }' file.csv
    SiegeX · 2009-02-16 21:32:46 0
  • - excel date compatible with a separate hour field - added a fixed 1 for easier request counter aggregation - split URL in directory, filename, fileext, query - used with tomcat valve with response bytes replaced by elapsed time Show Sample Output


    2
    #(see sample) $ cat x | perl -pe 'BEGIN{ print "TIME;...\n"; } s!(\S+) - (\S+) - \[(\d\d)/(\S\S\S)/(\S+):(\d\d):(\d\d:\d\d) \S+\] "(\S+) (.*/)(\S+)(?:\.([^?]*)(\?\S*)?) HTTP/\S+" (\d+) (\S+)!$3-$4-$5 $6:$7;$6;$2;$1;$8;$13;1;$14;$11;$10;$9;$12;!' > x.csv
    hute37 · 2012-02-10 16:58:50 0

What Others Think

For a single field, cut is way shorter: ls -l | cut -b3-6
netizen · 332 weeks and 1 day ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: