Showing posts with label Sysadmin. Show all posts
Showing posts with label Sysadmin. Show all posts

Bash String Tokenizing

Bash has some functionality to enable building a string tokenizer, by means of four modifiers:
  • #
  • ##
  • %
  • %%
We can then use to to get the first or last elements, from the end or the start of the string:

#!/bin/bash
TEST="i/am/a/very/big/dir"
echo ${TEST#*/}
echo ${TEST##*/}
echo ${TEST%/*}
echo ${TEST%%/*}

# am/a/very/big/dir
# dir
# i/am/a/very/big
# i

echo ${TEST#*/*/}
echo ${TEST%/*/*}

# a/very/big/dir
# i/am/a/very

I have omitted a leading slash in this string, which was a directory, so that it would print "i" instead of nothing. So you can use echo ${TEST%%/*}  to get the first element and saving echo ${TEST#*/} on every iteration of a cycle that tokenizes the string into an array.

The last two expressions serve to show that if you're dealing with some hardcoded delimiters, you can further expand it so that it matches what you want precisely.

Using Linux find Command

Most Linux distributions provide a file index which you can use to search for files. It is updated by the command 'updatedb', part of the "mlocate" package. 

For a quick way to find files inside a directory or subdirectory, the Linux "find" command from "findutils" can be used:
find directory -name filename
find will then return all the occurrences of the given 'filename'. You can use '/' as the directory path for it to recur into.
You can also search for files from a given user with a parameter:
find directory -user user
Or by files that end with a pattern:
find directory -name test*
You can also use it to help out with changing permissions on a directory and all files within, recursively, separating permissions from directories and files:
find /dir/to/chmod/all/dirs -type d -exec chmod 755 {} \;   # recursively changing dir permissions, ‘;’ is very important
find /dir/to/chmod/all/dirs -type f -exec chmod 644 {} \;
This is especially useful if you have messed up the file permissions by doing something like 'chmod -R 644' on directories and sub-directories within.