Search code examples
bashubuntuawkwhitespace

How to `awk` print a space-separated field which contains space characters?


I am trying to print the list of all files and folders including hidden files:

ls -al | awk -F' ' '{print $9}' | xargs do_something

However, some of the files and/or folders contain space characters. How could I achieve this? Thanks.


Solution

  • $ find . -mindepth 1 -maxdepth 1 -printf "%p\n"|xargs -i sh -c 'echo found: "{}"'
    found: ./file2
    found: ./folder 2
    found: ./folder
    found: ./file 1
    found: ./ file 3
    
    $ ls |awk '{print}'|xargs -i sh -c 'echo found "{}"'
    found: file2
    found: folder 2
    found: folder
    found: file 1
    
    $ ls |xargs -i sh -c 'echo found "{}"'
    found: file2
    found: folder 2
    found: folder
    found: file 1
    

    ls -A to list hidden files/folders too and exclude . and ..

    Using while loop for your backup

    #!/bin/bash
    
    DIR="/home"
    
    while IFS= read -r line; do 
        fullpath="$line"
        dirname=$(dirname "$line")
        basename=$(basename "$line")
        echo "$fullpath, $dirname, $basename"
        
    
        # your code
        # ...
    done < <( 
        find "${DIR}" -mindepth 1 -maxdepth 1 -printf "%T@ %p\n"| # print files/folders with TSP 
        sort -n|  # sort timestamp (maybe sort -nr)
        awk '{sub(/[^ ]+ /,"")}1' # remove first field (TSP)
    )