awk '{print $9}' the last ls -l column including any spaces in the file name

后端 未结 7 1292
星月不相逢
星月不相逢 2020-12-29 08:13

How would I get awk to output the whole file name in ls -l if some of the files have spaces in them. Usually, I can run this command:



        
相关标签:
7条回答
  • 2020-12-29 08:16

    If you still insist on the ls -l instead of find or other tools, here is my solution. It is not pretty and destructive:

    1. Destroy $1 .. $8 by setting them to "" via a for loop
    2. That leaves a bunch of spaces preceding $9, remove them using the sub() command
    3. Print out the remaining
    ls -l | awk '{for (i = 1; i < 9; i++) $i = ""; sub(/^ */, ""); print}'
    
    0 讨论(0)
  • 2020-12-29 08:18

    There's probably a better approach that involves combining fields somehow, but:

    $ echo 1 2 3 4 5 6 7 8 9 10 11 12 13 14... | 
      awk '{for (i = 9 ; i <= NF ; i++) printf "%s ", $i}'
    9 10 11 12 13 14... 
    

    Using printf "%s " $i will print the i-th field with a space after it, instead of a newline. The for loop just says to go from field 9 to the last field.

    0 讨论(0)
  • 2020-12-29 08:23

    A solution is to encode & decode the space with a word or character by using sed:

    ls -l | sed s/\ /{space}/ | awk '{print $9}' | sed s/{space}/\ /
    

    This will replace all spaces in a line with {space} before passing it to awk. After the line has passed to awk, we replace {space} back with space.

    find as stated by others is a much better solution. But if you really have to use awk, you can try this.

    0 讨论(0)
  • 2020-12-29 08:26

    A better solution: Don't attempt to parse ls output in the first place.

    The official wiki of the irc.freenode.org #bash channel has an explanation of why this is a Bad Idea, and what alternate approaches you can take instead: http://mywiki.wooledge.org/ParsingLs

    Use of find, stat and similar tools will provide the functionality you're looking for without the pitfalls (not all of which are obvious -- some occur only when moving to platforms with different ls implementations).

    For your specific example, I'm guessing that you're trying to find only files (and not directories) in your current directory; your current implementation using ls -l is buggy, as it excludes files which have +t or setuid permissions. The Right Way to implement this would be the following:

    find . -maxdepth 1 -type f -printf '%f\n'
    
    0 讨论(0)
  • 2020-12-29 08:26
    echo 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 | 
      awk 'BEGIN {OFS=ORS=""} ; {for (i=9;i<NF;i++) print $i " "; print $NF "\n"}'
    
    0 讨论(0)
  • 2020-12-29 08:27
    ls -l | awk -v x=9 '{print $x}'
    

    I use this for getting filenames of a directory without incident. I noted the find solution which is fine and dandy if you are unsure of the file types, if you know what you are looking at the ls -l works just fine, it also alphabetically orders by default.

    0 讨论(0)
提交回复
热议问题