How to take a string from a filename and use it as an argument
If the filename is in this format
assignment_number_username_filename.extension
Ref.
assignment_01_ssaha_homework1.txt
I only need to extract the username in order to use it in the rest of the script.
How to take just the username and use it as an argument.
This is close to what I'm looking for, but not exactly:
Extracting a string from a filename
if someone can explain how sed works in this scenario, that would be just as helpful!
That's what I have so far; I haven't used it cut
in a while, so I get error messages trying to update myself.
#!/bin/sh
a = $1
grep $a /home | cut -c 1,2,4,5 echo $a`
source to share
You probably want command substitution, plus echo
plus sed
. You should be aware that regular expressions sed
can remember parts of a match. And you need to know basic regular expressions. In context, this adds:
filename="assignment_01_ssaha_homework1.txt"
username=$(echo "$file" | sed 's/^[^_]*_[^_]*_\([^_]*\)_[^.]*\.[^.]*$/\1/')
Notation $(...)
is command substitution. The commands between the parentheses are executed and the output is written as a string. In this case, the string is assigned to a variable username
.
In a command, a sed
general command applies a specific substitution ( s/match/replace/
) operation to each line of input (here it will be one line). The components of the [^_]*
regular expression match a sequence (zero or more) of non-underscores. The part \(...\)
remembers a closed regular expression (third sequence of characters without underscore, the so-called username). Switching to [^.]*
at the end recognizes the change in delimiter from underscore to period. The replacement text \1
replaces the entire name with the memory portion of the template. In general, you can have several memorable subsections of a template. If the filename doesn't match the pattern, you get the input as a result.
There bash
are ways to avoid echo
; you could use some of the more esoteric (which means "not available in other shells") mechanisms to retrieve data. This will work on most modern POSIX shells (Korn, Bash, and others).
source to share
Just bash:
filename="assignment_01_ssaha_homework1.txt"
tmp=${filename%_*}
username=${tmp##*_}
http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion
source to share