Bash: Pattern matchin - how to do matching on a variable?
This is similar to the question asked on thread: http://www.linuxquestions.org/questi...-bash.-691571/
However, it's a bit different. In perl, the code would be: Code:
my $outPut = `ls -ltr foo`; |
awk would be well suited for this:
Code:
ls -ltr | awk '{ print $8 }' Or, sometimes I do something like this with grep: Code:
if [ `echo $foo | grep -Ec "regex"` -eq 1 ]; then |
Same way described by ntubski in that thread - regex pattern matching. You can access the parenthesized matches in the BASH_REMATCH array.
|
My point as well. You can use just:
Code:
ls -tr foo Code:
ls -1tr |
is getting file names so difficult? use shell expansion, and DON'T use ls -l + awk to get file names unless you are pretty sure files don't have spaces.
Code:
for myfile in * |
Actually, you should *never* try to do any kind of parsing with the output of ls - http://mywiki.wooledge.org/ParsingLs
|
8 columns--more if the file is a link
For the filename: Code:
ls -l|sed -r 's/ +/ /g'|cut -d " " -f8 |
Quote:
|
Quote:
|
Quote:
Possibly over-defensive in many real-life situations and surely slow but appealing to those of us given aversion therapy in the school of "if it can go wrong, it will go wrong". |
well, ls uses the same "stat" libraries to retrieve those information as well. Also, stat may not be in some Unix platforms, but ls is.
|
Quote:
The "sweet spot" will vary depending on usage -- a quick-and-dirty "one off", a cross-platform installation utility, a backup script, system-wide vs. private usage etc. Are there many *n*x platforms that don't have stat -- apart from very cut-down versions such as BusyBox (which may have stat -- I don't know)? |
Quote:
If use the code above, it seems to work, as long as the filename does not have spaces in the filename . Quote:
Quote:
|
Quote:
Quote:
|
SQADude is saying that
ls -l always produces one 'record' per file per line of output, and anything(!) after the date/timestamp in each rec is the filename, with or without spaces in it. |
All times are GMT -5. The time now is 03:12 PM. |