Friday, 20 December 2024

sed on FreeBSD file listing

sed can be used to modify a FreeBSD file listing with regular expressions, allowing you to convert an ls into a csv, for example.

Given a file listing like:

-rwxr-xr-x   1 Andrew.Potts  wheel   7417965 Apr 12  2023 file1.jpg

-rwxr-xr-x   1 Andrew.Potts  wheel  13536345 Apr 12  2023 file2.jpg

-rwxr-xr-x   1 Andrew.Potts  wheel  11488336 Apr 12  2023 file3.jpg

You can create and test the regular expressions on Sed Tester: https://sed.js.org/

Note however, early versions of FreeBSD don't support characters like \s, \S or \d.
Instea you must use commands like [:alpha:]

ls -la | sed -E 's/^([-drwx\+]*)[[:space:]]+([0-9]+)[[:space:]]+([[:alpha:].]+)[[:space:]]+([[:alpha:]]+)[[:space:]]+([[:digit:]]+)[[:space:]]+([[:alpha:]]+[[:space:]]+[[:digit:]]+[[:space:]]+[[:digit:]]+)[[:space:]]+(.+)$/\7,\5,\6/p'



's/\(.* [A-Za-z]* [0-9]*\) \([0-9]*\) \([a-z|A-Z]* [0-9]* [0-9]*:[0-9]*\) \(.*\)/\4,\2,\3/'

 ls -la | sed -E 's/^([-drwx\+]*)[[:space:]]+([0-9]+)[[:space:]]+([[:alpha:].]+)(.+)$/\3/p'

Capture 

([-rwx]*)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\w+\s+\d+\s+\d+)\s+(.+)$

--regexp-extended --expression='s/^([-rwx]*)\s+([0-9]+)\s+(\S+)\s+(\S+)\s+([0-9]+)\s+(\S+\s+[0-9]+\s+[0-9]+)\s+(.+)$/\5,\6,\7/'


These chained commands:

    find "/mnt/Data/My Media/Karate/" -type f -exec stat -f "%N@%z@%SB" -t "%Y/%m/%d %H:%M:%S" {} \; | sed -E 's|^(.*[\\/])([^\\/]+)@(.*)@(.*)|\2,\1\2,\3,\4|'

  • finds the files in the directiories and subdirectories
  • retrieves the full path, size and formatted date, separated by the @ character
  • runs a regex over the result to extract the filename (\2), path and filename (\2\1), size (\3) and date (\4), comma-separating the results



No comments:

Post a Comment